title
stringlengths
3
46
content
stringlengths
0
1.6k
19:520
protected override void OnInitialized()
19:521
{
19:522
...
19:523
}
19:524
protected override async Task OnInitializedAsync()
19:525
{
19:526
await ...
19:527
}
19:528
19:529
They are called once in the component lifetime, immediately after the component has been created and added to the render tree. Please place any initialization code there, and not in the component constructor, as this will improve component testability. This is because there, you have all parameters set and future Blazor versions might pool and reuse component instances.
19:530
If the initialization code subscribes to some events or performs actions that need a cleanup when the component is destroyed, implement IDisposable, and place all the cleanup code in its Dispose method. Whenever a component implements IDisposable, Blazor calls its Dispose method before destroying it.
19:531
After the component has been initialized, and each time a component parameter changes, the following two methods are called:
19:532
protected override async Task OnParametersSetAsync()
19:533
{
19:534
await ...
19:535
}
19:536
protected override void OnParametersSet()
19:537
{
19:538
...
19:539
}
19:540
19:541
They are the right place to update data structures that depend on the values of the component parameters.
19:542
After that, the component is rendered or re-rendered. You can prevent component re-rendering after an update by overriding the ShouldRender method:
19:543
protected override bool ShouldRender()
19:544
{
19:545
...
19:546
}
19:547
19:548
Letting a component re-render only if you are sure its HTML code will change is an advanced optimization technique used in the implementation of component libraries.
19:549
The component rendering stage also involves the invocation of its children components. Therefore, component rendering is considered complete only after all its descendant components have completed their rendering too. When rendering is complete, the following methods are called:
19:550
protected override void OnAfterRender(bool firstRender)
19:551
{
19:552
if (firstRender)
19:553
{
19:554
}
19:555
...
19:556
}
19:557
protected override async Task OnAfterRenderAsync(bool firstRender)
19:558
{
19:559
if (firstRender)
19:560
{
19:561
await...
19:562
...
19:563
}
19:564
await ...
19:565
}
19:566
19:567
Since when the preceding methods are called, all component HTML has been updated and all children components have executed all their lifetime methods, the preceding methods are the right places for performing the following operations:
19:568
19:569
Calling JavaScript functions that manipulate the generated HTML. JavaScript calls are described in the JavaScript interoperability subsection.
19:570
Processing information attached to parameters or cascaded parameters by descendant components. In fact, tab-like components and other components might need to register some of their subparts in the root component, so the root component typically cascades a data structure where some children components can register. Code written in AfterRender and AfterRenderAsync can rely on the fact that all the parts have completed their registration.
19:571
19:572
The next section describes Blazor tools for collecting user input.
19:573
Blazor forms and validation
19:574
Similar to all major SPA frameworks, Blazor offers specific tools for processing user input while providing valid feedback to the user with error messages and immediate visual clues.
19:575
In classic HTML websites, HTML forms are used to collect input, validate it, and send it to the server. In client frameworks, data is not sent to the server by submitting forms, but forms retain their validation purpose. More specifically, they act as validation units, that is, as a container for inputs that must be validated together because they belong to a unique task. Accordingly, when a submit button is clicked, an overall validation is performed, and the system notifies of the result via events. This way, the developer can define what to do in case of errors and what actions to take when the user has successfully completed their input.
19:576
19:577
It is worth pointing out that validation performed on the client side doesn’t ensure data integrity because a malicious user could easily hack all client validation rules because they have full access to the client-side code in their browser. The purpose of client-side validation is just to provide immediate feedback to the user.
19:578
19:579
Accordingly, the validation step must be repeated on the server side to enforce data integrity.
19:580
Both server-side and client-side validation can be performed with the same code shared between the Blazor client and the server. In fact, both the ASP.NET Core REST API and Blazor support validation based on validation attributes, so it is enough to share the same ViewModels equipped with validation attributes between the Blazor and server projects by putting them in a library that is referenced by both projects. ASP.NET Core validation is discussed in the Server-side and client-side validation section of Chapter 17, Presenting ASP.NET Core.
19:581
The whole toolset is known as Blazor Forms and consists of a form component called EditForm, various input components, a data annotation validator, a validation error summary, and validation error labels.
19:582
EditForm takes care of orchestrating the state of all input components through an instance of the EditContext class that is cascaded inside of the form. The orchestration comes from the interaction of both input components and the data annotation validator with this EditContext instance. A validation summary and error message labels don’t take part in the orchestration but register to some EditContext events to be informed about errors.
19:583
EditForm must be passed the object whose properties must be rendered in its Model parameter. It is worth pointing out that input components bound to nested properties are not validated, so EditForm must be passed a flattened ViewModel. EditForm creates a new EditContext instance, passes the object received in its Model parameter in its constructor, and cascades it so it can interact with the form content.
19:584
You can also directly pass an EditContext custom instance in the EditContext parameter of EditForm instead of passing the object in its Model parameter, in which case EditForm will use your custom copy instead of creating a new instance. Typically, you do this when you need to subscribe to the EditContext OnValidationStateChanged and OnFieldChanged events.
19:585
When EditForm is submitted with a Submit button and there are no errors, the form invokes its OnValidSubmit callback, where you can place the code that uses and processes the user input. If instead there are validation errors, they are displayed, and the form invokes its OnInvalidSubmit callback.
19:586
The state of each input is reflected in some CSS classes that are automatically added to them, namely valid, invalid, and modified. You can use these classes to provide adequate visual feedback to the user. The default Blazor template already provides some CSS for them.
19:587
Here is a typical form:
19:588
<EditForm Model=`FixedInteger`OnValidSubmit=`@HandleValidSubmit` >
19:589
<DataAnnotationsValidator />
19:590
<ValidationSummary />
19:591
<div class=`form-group`>
19:592
<label for=`integerfixed`>Integer value</label>
19:593
<InputNumber @bind-Value=`FixedInteger.Value`
19:594
id=`integerfixed` class=`form-control` />
19:595
<ValidationMessage For=`@(() => FixedInteger.Value)` />
19:596
</div>
19:597
<button type=`submit` class=`btn btn-primary`> Submit</button>
19:598
</EditForm>
19:599
19:600
The label is a standard HTML label, while InputNumber is a Blazor-specific component for number properties. ValidationMessage is the error label that appears only in the event of a validation error. By default, it is rendered with a validation-message CSS class. The property associated with the error message is passed in the for parameter with a parameterless lambda, as shown in the example.
19:601
The DataAnnotationsValidator component adds a validation based on the usual .NET validation attributes, such as RangeAttribute, RequiredAttribute, and so on. You can also write your custom validation attributes by inheriting from the ValidationAttribute class.
19:602
You can provide custom error messages in the validation attributes. If they contain a {0} placeholder, this will be filled with the property display name declared in a DisplayAttribute, if one is found, otherwise with the property name.
19:603
Together with the InputNumber component, Blazor also supports an InputText component for string properties, an InputTextArea component for string properties to be edited in an HTML textarea, an InputCheckbox component for bool properties, and an InputDate component that renders DateTime and DateTimeOffset as dates. They all work in exactly the same way as the InputNumber component. No component is available for other HTML5 input types. In particular, no component is available for rendering time or date and time, or for rendering numbers with a range widget.
19:604
If you need HTML5 inputs that are not available as Blazor input form components, you are left with the option of implementing them yourself or of using a third-party library that supports them.
19:605
You can implement rendering time or date and time by inheriting from the InputBase<TValue> class and overriding the BuildRenderTree, FormatValueAsString, and TryParseValueFromString methods. The sources of the InputNumber component show how to do this: https://github.com/dotnet/aspnetcore/blob/main/src/Components/Web/src/Forms/InputNumber.cs. You can also use the third-party libraries described in the Third-party tools for Blazor WebAssembly section.
19:606
Blazor also has a specific component for rendering a select, which works as in the following example:
19:607
<InputSelect @bind-Value=`order.ProductColor`>
19:608
<option value=``>Select a color ...</option>
19:609
<option value=`Red`>Red</option>
19:610
<option value=`Blue`>Blue</option>
19:611
<option value=`White`>White</option>
19:612
</InputSelect>
19:613
19:614
Starting from .NET 6, InputSelect can also be bound to IEnnumerable<T> properties, in which case it is rendered as a multi-select.
19:615
One can also render enumerations with a radio group thanks to the InputRadioGroup and InputRadio components, as shown in the following example:
19:616
<InputRadioGroup Name=`color` @bind-Value=`order.Color`>
19:617
<InputRadio Name=`color` Value=`AllColors.Red` /> Red<br>
19:618
<InputRadio Name=`color` Value=`AllColors.Blue` /> Blue<br>
19:619
<InputRadio Name=`color` Value=`AllColors.White` /> White<br>