Handle events

Blazor components often handle UI events. To specify an event callback for an event from a UI element, you use an attribute that starts with @on and ends with the event name. For example, you can specify the IncrementCount method as a handler for a button click event using the @onclick attribute, like this:

razorCopy

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

You can specify C# event handlers for other HTML events too, like @onchange@oninput, and so on. Event handling methods can be synchronous or asynchronous. You can also define event handlers inline using C# lambda expressions:

razorCopy

<button class="btn btn-primary" @onclick="() => currentCount++">Click me</button>

Event handler methods can optionally take an event argument with information about the event. For example, you can access the value of an input element that changed, like this:

razorCopy

<input @onchange="InputChanged" />
<p>@message</p>

@code {
    string message = "";

    void InputChanged(ChangeEventArgs e)
    {
        message = (string)e.Value;
    }
}

After an event handler runs, Blazor will automatically render the component with its new state, so the message is displayed after the input changes.

Data binding

Often you want the value of a UI element to be bound to a particular value in code. When the value of the UI element changes, the code value should change, and when the code value changes the UI element should display the new value. Blazor’s data binding support makes it easy to set up this sort of two-way data binding.

You bind a UI element to a particular value in code using the @bind attribute. For example:

razorCopy

<input @bind="text" />
<button @onclick="() => text = string.Empty">Clear</button>
<p>@text</p>

@code {
    string text = "";
}

When you change the value of the input, the text field is updated with the new value. And when you change the value of the text field by clicking the Clear button, the value of the input is also cleared.

red hat certification malaysia

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *