Search code examples
c#razorblazor

How do i get blazor's onclick event to work?


I've got a pretty simple logon page setup but for some reason the onclick isn't running the test method that it should be. It's not returning any warnings or errors but still isn't printing to the console the code is as follows:

@page "/logon"
<div class="container">
<div class="login-box">
    <!-- Image -->
    <img src="/Images/welcome2s2ix.png" alt="Login Image" class="login-image" />

    <!-- Login Form -->
    <form>
        <div class="form-group row">
            <div class="col-sm-12">
                <label for="username">Username</label>
            </div>
            <div class="col-sm-12">
                <input type="text" id="username" class="form-control" placeholder="Enter your username" />
            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-12">
                <label for="password">Password</label>
            </div>
            <div class="col-sm-12">
                <input type="password" id="password" class="form-control" placeholder="Enter your password" />
            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-12">
                <label for="logonTo" class="col-sm-2 col-form-label">Database</label>
            </div>
            <div class="col-sm-10">
                <select id="logonTo" class="form-control">
                    <option value="local">Local</option>
                </select>
            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-12">
                <button type="submit" @onclick="test" class="btn btn-primary">Login</button>
            </div>
        </div>
    </form>
</div>
@code {
public void test()
{
    Console.WriteLine("Test");

}

I've checked a whole heap of pages that say to check your _Imports.razor but they look okay as well... not sure what's going on here.


Solution

  • You are using a button of type="submit this submits the form. If you want to process the forms contents I would change the form to EditForm as it will intercept the form posting. Then move the method call to the EditForm's OnValidSubmit or OnSubmit. Please read up on EditForm and its sibling components InputText, InputCheckbox ect.

    If you change the <Button to type="button" your code should execute but the form will not be submitted.