受欢迎的博客标签

ASP.NET Core Razor Components-Event Handling

Published

With ASP.NET Core Razor Components you can take advantage of event-driven programming by using event binding. This is achieved with HTML event attributes like, onclick, onchange, and onkeypress.

You must specify the method you want to call on the event attribute ,for example:

onclick="@YourMethod"

 If you need to pass arguments to your method, you must use a Lambda expression,for example:

onclick="@(() => YourMethod(someArgument, anotherArgument))"

you can access event-specific arguments supported by ASP.NET Core Razor Components.ASP.NET Core Razor Components supports the following event arguments:

UIEventArgs
UIChangeEventArgs
UIKeyboardEventArgs
UIMouseEventArgs

 

Blazor onchange event with select dropdown

https://stackoverflow.com/questions/49947790/blazor-onchange-event-with-select-dropdown

cshtml:

<select onchange=@DoStuff>
    @foreach (var template in templates)
    {
        <option value=@template>@template</option>
    }
</select>
@functions {
    List<string> templates = new List<string>() { "Maui", "Hawaii", "Niihau", "Kauai", "Kahoolawe" };
    string selectedString = "Maui";

    void DoStuff(UIChangeEventArgs e)
    {
        selectedString = e.Value.ToString();
        Console.WriteLine("It is definitely: " + selectedString);
    }
}

You could also just use a bind <select bind="@selectedString"> ,but onchange=@DoStuff allows you to perform logic on selection.

 

Mouse

mouse click

mouse move

<h1 class="display-1" onmouseover="@OnMouseOver" onmouseout="@OnMouseOut">@inOrOut</h1>