Skip to content

Blazor Razor components: parameters, events, forms

Blazor UI is built from Razor components: .razor files that combine HTML markup with C# logic and compile into .NET classes. Every page, layout and reusable widget is a component, and the same component code runs whether it is rendered statically on the server, interactively over a server connection, or in the browser on WebAssembly (see hosting models and render modes). This page covers writing components, passing data in and events out, binding forms with validation, and the lifecycle methods that load data. The examples are parts of OrdersPortal, an invented order-management app.

The samples target .NET 10 (LTS) and work unchanged on .NET 11 (STS, November 2026). They were compiled with the .NET SDK 10.0.115 and rendered with bUnit 2.15, a component testing library, from a small console program; the driver code for each sample is shown with it, and the output is what that program printed. The shared model types are:

Models.cs
public enum OrderStatus { Open, Shipped, Cancelled }
public record OrderLine(string Sku, string Name, decimal UnitPrice, int Quantity);
public record Order(int Id, string Customer, OrderStatus Status, List<OrderLine> Lines);
// Program.cs: driver setup (bUnit 2.15)
using Microsoft.Extensions.DependencyInjection;
using Bunit;
using RazorDemo;
using var ctx = new BunitContext();
ctx.Services.AddSingleton<IOrderService, FakeOrderService>();
Topic Use it to
Razor component basics Write markup with C# expressions, conditionals and loops.
Parameters and event callbacks Pass data into a component and notify the parent of changes.
Data binding and forms Bind inputs with @bind and validate with EditForm.
Component lifecycle Load data, react to new parameters and clean up.

A Razor component is a .razor file whose name, starting with a capital letter, becomes the component’s class name (OrderCard.razor is used as <OrderCard />). The markup section mixes HTML with Razor syntax: @expression writes a value (HTML-encoded), @(...) wraps a longer expression, and @if, @foreach and @switch blocks control output. The @code { } block holds fields, properties and methods of the component class; you can also move it to a partial class in OrderCard.razor.cs. Directives at the top configure the component: @page "/orders/{Id:int}" makes it routable, @inject gets services from dependency injection, @using imports namespaces and @implements adds interfaces.

The framework re-renders a component after its event handlers and lifecycle methods run, compares the new render tree with the previous one and applies only the differences to the DOM, much like React’s virtual DOM. Component-scoped CSS goes in OrderCard.razor.css and is isolated to that component at build time.

@* OrderCard.razor *@
<article class="order-card @StatusCss">
<h3>Order @Order.Id</h3>
<p>@Order.Customer, @Order.Lines.Count lines, @Total.ToString("0.00") EUR</p>
@if (Order.Status == OrderStatus.Open)
{
<span class="badge">Awaiting shipment</span>
}
</article>
@code {
[Parameter, EditorRequired]
public Order Order { get; set; } = default!;
private decimal Total => Order.Lines.Sum(l => l.UnitPrice * l.Quantity);
private string StatusCss => Order.Status.ToString().ToLowerInvariant();
}
// 1. Parameters: render a component with an Order parameter.
var order = new Order(1001, "Ada Lopez", OrderStatus.Open,
[new("SKU-RED-01", "Red mug", 19.99m, 2), new("SKU-BLU-07", "Blue coaster", 5.50m, 4)]);
Console.WriteLine(ctx.Render<OrderCard>(p => p.Add(c => c.Order, order)).Markup);

Output:

<article class="order-card open"><h3>Order 1001</h3>
<p>Ada Lopez, 2 lines, 61.98 EUR</p><span class="badge">Awaiting shipment</span></article>

Pitfalls:

  • Heavy logic in markup. Long expressions inside @( ) are hard to test; move them to properties such as Total.
  • MarkupString with user data. Casting a string to MarkupString renders raw HTML and bypasses encoding; never do it with user input.
  • Lower-case file names. A component file must start with an upper-case letter, otherwise it is treated as an HTML element.

Parameters are public properties marked [Parameter] that the parent sets as attributes: <OrderLineRow Line="line" />. Mark required ones with [EditorRequired] so the compiler warns when they are missing. Data flows down through parameters; changes flow up through EventCallback or EventCallback<T> parameters that the parent assigns a method to. EventCallback is preferred over a plain Action because invoking it re-renders the parent (the component that owns the handler) automatically and supports async handlers.

A component must never assign to its own parameter properties: when the parent re-renders, it overwrites them, and the change is lost. Raise an event and let the owner update its state, as OrderLineRow does. Use @key in loops so Blazor matches list items by identity rather than position when items are inserted or removed. For values needed deep in a tree, such as the current user or theme, <CascadingValue> and [CascadingParameter] avoid passing parameters through every level.

@* OrderLineRow.razor *@
<li class="line">
<span>@Line.Name</span>
<button type="button" class="dec" @onclick="() => ChangeQuantity(-1)" disabled="@(Line.Quantity <= 1)">-</button>
<span class="qty">@Line.Quantity</span>
<button type="button" class="inc" @onclick="() => ChangeQuantity(+1)">+</button>
<button type="button" class="remove" @onclick="() => OnRemove.InvokeAsync(Line.Sku)">Remove</button>
</li>
@code {
[Parameter, EditorRequired] public OrderLine Line { get; set; } = default!;
[Parameter] public EventCallback<OrderLine> OnChanged { get; set; }
[Parameter] public EventCallback<string> OnRemove { get; set; }
// Never assign to a [Parameter] property: raise an event and let the owner update.
private Task ChangeQuantity(int delta) =>
OnChanged.InvokeAsync(Line with { Quantity = Line.Quantity + delta });
}
@* OrderLinesEditor.razor *@
<ul>
@foreach (var line in lines)
{
<OrderLineRow @key="line.Sku" Line="line" OnChanged="Replace" OnRemove="Remove" />
}
</ul>
<p class="summary">@lines.Count lines, @lines.Sum(l => l.Quantity) items, @lines.Sum(l => l.UnitPrice * l.Quantity).ToString("0.00") EUR</p>
@code {
private List<OrderLine> lines =
[
new("SKU-RED-01", "Red mug", 19.99m, 2),
new("SKU-BLU-07", "Blue coaster", 5.50m, 4),
];
private void Replace(OrderLine updated) =>
lines = lines.Select(l => l.Sku == updated.Sku ? updated : l).ToList();
private void Remove(string sku) => lines.RemoveAll(l => l.Sku == sku);
}
// 2. Event callbacks: click + on the first row, then Remove on the second.
var editor = ctx.Render<OrderLinesEditor>();
string Summary() => editor.Find(".summary").TextContent;
Console.WriteLine(Summary());
editor.FindAll("button.inc")[0].Click();
Console.WriteLine(Summary());
editor.FindAll("button.remove")[1].Click();
Console.WriteLine(Summary());

Output:

2 lines, 6 items, 61.98 EUR
2 lines, 7 items, 81.97 EUR
1 lines, 3 items, 59.97 EUR

Pitfalls:

  • Writing to a parameter (Line.Quantity++ on a mutable model, or Line = ...) is overwritten on the next parent render; raise an event instead.
  • Many fine-grained parameters of complex types. Blazor cannot tell whether a mutable object changed, so it re-renders children that receive one; prefer immutable records or primitive parameters for hot paths.
  • Missing @key in dynamic lists can attach a row’s element state to the wrong item after a removal.

@bind creates two-way binding between an element and a field: <input @bind="search" /> writes the field on change, and @bind:event="oninput" updates on every keystroke. @bind:after runs a method after the value is written. On components, @bind-Value binds a component parameter and its ValueChanged callback.

Forms use EditForm with a model object. Built-in input components (InputText, InputNumber, InputSelect, InputDate, InputCheckbox) bind with @bind-Value, convert types and add CSS classes for validation state. DataAnnotationsValidator applies attributes such as [Required], [Range] and [EmailAddress]; ValidationMessage and ValidationSummary show errors; OnValidSubmit runs only when validation passes. In static server rendering, a form posts like a classic HTML form, so it needs a unique FormName and receives the posted model through [SupplyParameterFromForm]. Initialize that model in OnInitialized with ??= rather than a property initializer, which a post can overwrite with null (analyzer BL0008). .NET 11 adds client-side validation feedback for static SSR forms and asynchronous validation rules.

@* ReturnRequestForm.razor *@
<EditForm Model="Request" OnValidSubmit="SubmitAsync" FormName="return-request">
<DataAnnotationsValidator />
<label>Order number <InputNumber @bind-Value="Request!.OrderId" /></label>
<ValidationMessage For="() => Request!.OrderId" />
<label>Email <InputText @bind-Value="Request!.Email" /></label>
<ValidationMessage For="() => Request!.Email" />
<label>
Reason
<InputSelect @bind-Value="Request!.Reason">
<option value="">Choose...</option>
<option value="Damaged">Damaged</option>
<option value="WrongItem">Wrong item</option>
</InputSelect>
</label>
<ValidationMessage For="() => Request!.Reason" />
<button type="submit" disabled="@saving">Request return</button>
</EditForm>
@if (confirmation is not null)
{
<p class="confirmation">@confirmation</p>
}
@code {
// Filled from the posted form in static SSR; no property initializer (analyzer BL0008).
[SupplyParameterFromForm] private ReturnRequest? Request { get; set; }
private bool saving;
private string? confirmation;
protected override void OnInitialized() => Request ??= new();
private async Task SubmitAsync()
{
saving = true;
await Task.Delay(10); // stand-in for a call to the orders API
confirmation = $"Return requested for order {Request!.OrderId} ({Request!.Reason})";
saving = false;
}
public class ReturnRequest
{
[Range(1, int.MaxValue, ErrorMessage = "Enter an order number")]
public int OrderId { get; set; }
[Required, EmailAddress(ErrorMessage = "Enter a valid email")]
public string? Email { get; set; }
[Required(ErrorMessage = "Choose a reason")]
public string? Reason { get; set; }
}
}
// 3. Forms: submit empty, then fill in valid values and submit again.
var form = ctx.Render<ReturnRequestForm>();
form.Find("form").Submit();
Console.WriteLine(string.Join(" | ", form.FindAll(".validation-message").Select(e => e.TextContent)));
form.Find("input[type=number]").Change("1001");
form.Find("input:not([type=number])").Change("ada@example.test");
form.Find("select").Change("Damaged");
form.Find("form").Submit();
form.WaitForElement(".confirmation");
Console.WriteLine(form.Find(".confirmation").TextContent);

Output:

Enter an order number | The Email field is required. | Choose a reason
Return requested for order 1001 (Damaged)

Pitfalls:

  • Assigning both Model and EditContext on EditForm throws at runtime; use one.
  • Validation only in the UI. The API that saves the return must validate again; a client can bypass the form.
  • Disabled submit as the only double-submit guard. In static SSR there is no interactivity to disable the button; make the server operation idempotent.

Blazor calls lifecycle methods in a fixed order. SetParametersAsync assigns parameters; OnInitialized{Async} runs once when the component is first created, the usual place to load data that does not depend on changing parameters; OnParametersSet{Async} runs after the first initialization and again whenever the parent passes new parameter values, the right place to load data keyed by a parameter such as OrderId. After each render, OnAfterRender{Async}(firstRender) runs, which is where JavaScript interop belongs, because the DOM exists only then. Implement IDisposable or IAsyncDisposable to unsubscribe from events and cancel work when the component is removed.

When an async lifecycle method awaits, Blazor renders the current state first (for example “Loading…”) and renders again when the task completes. Interactive components that are prerendered run their initialization twice, once during prerendering and once when they become interactive, unless you persist the state with [PersistentState] (.NET 10) or PersistentComponentState.

@* OrderHeader.razor *@
@implements IDisposable
@inject IOrderService Orders
@if (order is null)
{
<p class="status">@(loading ? $"Loading order {OrderId}..." : $"Order {OrderId} not found")</p>
}
else
{
<h2 class="status">Order @order.Id for @order.Customer</h2>
}
@code {
[Parameter] public int OrderId { get; set; }
private Order? order;
private bool loading;
private CancellationTokenSource? cts;
protected override void OnInitialized() => Console.WriteLine(" OnInitialized");
// Runs on first render and whenever the parent passes new parameters.
protected override async Task OnParametersSetAsync()
{
Console.WriteLine($" OnParametersSetAsync({OrderId})");
cts?.Cancel(); // cancel the previous load
cts = new CancellationTokenSource();
var token = cts.Token;
(order, loading) = (null, true);
try
{
order = await Orders.GetOrderAsync(OrderId, token);
loading = false;
}
catch (OperationCanceledException)
{
Console.WriteLine(" previous load cancelled");
}
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender) Console.WriteLine(" OnAfterRender(firstRender: true)");
}
public void Dispose()
{
cts?.Cancel();
cts?.Dispose();
Console.WriteLine(" Dispose");
}
}
IOrderService.cs
public interface IOrderService
{
Task<Order?> GetOrderAsync(int id, CancellationToken cancellationToken);
}
public sealed class FakeOrderService : IOrderService
{
public async Task<Order?> GetOrderAsync(int id, CancellationToken cancellationToken)
{
Console.WriteLine($" service: loading order {id}");
await Task.Delay(id == 1001 ? 200 : 20, cancellationToken);
return id is 1001 or 1002 ? new Order(id, id == 1001 ? "Ada Lopez" : "Ben Ortiz", OrderStatus.Open, []) : null;
}
}
// 4. Lifecycle: load 1001, switch to 1002 before it finishes, then 9999, then dispose.
var header = ctx.Render<OrderHeader>(p => p.Add(c => c.OrderId, 1001));
Console.WriteLine(header.Find(".status").TextContent);
header.Render(p => p.Add(c => c.OrderId, 1002));
header.WaitForElement("h2");
Console.WriteLine(header.Find(".status").TextContent);
header.Render(p => p.Add(c => c.OrderId, 9999));
header.WaitForState(() => header.Find(".status").TextContent.Contains("not found"));
Console.WriteLine(header.Find(".status").TextContent);
await ctx.DisposeComponentsAsync();

Output:

OnInitialized
OnParametersSetAsync(1001)
service: loading order 1001
OnAfterRender(firstRender: true)
Loading order 1001...
OnParametersSetAsync(1002)
service: loading order 1002
previous load cancelled
Order 1002 for Ben Ortiz
OnParametersSetAsync(9999)
service: loading order 9999
Order 9999 not found
Dispose

Switching from 1001 to 1002 cancelled the slow first request, so the stale order could not overwrite the new one, and disposing the component cancelled anything still running.

Pitfalls:

  • Loading parameter-dependent data in OnInitializedAsync. It runs once; when the route changes from /orders/1001 to /orders/1002 on the same page component, use OnParametersSetAsync.
  • JavaScript interop in OnInitialized. The DOM does not exist yet, and during prerendering there is no browser at all; use OnAfterRenderAsync(firstRender).
  • async void handlers. Exceptions escape the renderer; return Task so Blazor can await and report errors.
Need Use
Parent supplies a value [Parameter], with [EditorRequired] when mandatory
Child reports a change EventCallback<T>
Two-way binding to a child component Value plus ValueChanged parameters and @bind-Value
Value shared by a deep subtree CascadingValue and [CascadingParameter]
App-wide state across pages A scoped DI service that raises change events
Forms with validation EditForm, input components and DataAnnotationsValidator

Why use EventCallback instead of Action for component events? EventCallback knows which component owns the handler, so after invoking it Blazor re-renders that component, and it supports async handlers with proper error flow. With an Action, the parent’s state changes but it does not re-render unless you call StateHasChanged yourself.

What is the difference between OnInitializedAsync and OnParametersSetAsync? OnInitializedAsync runs once per component instance. OnParametersSetAsync runs after initialization and every time new parameters arrive, so data that depends on a parameter, such as an order ID from the route, must load there.

When do you call StateHasChanged manually? Only when state changes outside Blazor’s own event and lifecycle flow, such as a timer callback, a service event or a SignalR message. In those cases call InvokeAsync(StateHasChanged) to marshal onto the renderer’s synchronization context.

Why does a prerendered interactive component load its data twice, and how do you avoid it? Prerendering creates the component on the server to produce HTML, then a second instance starts when the circuit or WebAssembly runtime becomes interactive. Persist the loaded data with [PersistentState] or PersistentComponentState so the interactive instance reuses it, or disable prerendering for that component.

Senior scenario: the order grid in an Interactive Server app becomes sluggish with 2,000 rows and frequent updates. What do you change? Profile first, then reduce render work: virtualize the list with <Virtualize> (or QuickGrid with virtualization), pass immutable records and add @key, override ShouldRender or split rows into components so one update re-renders one row, and debounce @bind:event="oninput" filters. Reduce traffic over the circuit by paging data from the server, and consider moving the grid to WebAssembly if latency dominates.