Let’s explore how to define component rendering logic and handle UI events.
Render C# expression values
When you want to render the value of a C# expression in Razor, you use a leading @ character. For example, a Counter component can render the value of its currentCount field like this:
razorCopy
<p role="status">Current count: @currentCount</p>
Razor can typically figure out when a C# expression ends and you transition back to writing HTML. But you can also be explicit about the beginning and ending of the expression using parens.
razorCopy
<p role="status">Current count: @(currentCount)</p>
Add control flow
You can add control flow to your component rendering logic using normal C# statements. For example, you can conditionally render some content using a C# if-statement, like this:
razorCopy
@if (currentCount > 3)
{
<p>You win!</p>
}
You can also use C# to loop over data and render a list of items:
razorCopy
<ul>
@foreach (var item in items)
{
<li>@item.Name</li>
}
</ul>
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.
Leave a Reply