Controlling the rendering using the @key directive
When it comes to rendering collections by iterating over the items and rendering some UI elements, the powerful mechanism of Blazor RenderTree
and its diffing algorithm will observe the changes happening to the list (insert, update, and delete) and update the UI accordingly. Blazor assigning and indexing for each item gets rendered in the UI based on the items in the list at runtime. That’s the normal approach for most cases.
Because the sequence numbers are assigned at runtime, Blazor will start sequentially from the first item in the list to the last. So, let’s create a sample component that will simulate the scenario, as follows:
- In the
Pages
folder, create a Razor component and call itkey-directive-sample.razor
. - Write the following code inside it:
@page "/key-directive-sample"<h3>Key Attribute Sample</h3><ul> @foreach (var item in numbers) ...