SkillPilotAI

Blazor basics

Blazor builds web UI with C# Razor components. In a Blazor Web App every component is Static SSR by default, so the render mode you choose (Server, WebAssembly or Auto) decides whether clicks work and where your code runs.

66.1 Why is it used?

  • In the demo the Cart button is wired to Add, but three clicks still show Items: 0 and no error.
  • Reason: the default is Static SSR; the server builds HTML once and the browser gets a plain button with no handler.
  • To make it interactive, give the component an interactive render mode.
  • Blazor lets you write the UI and its logic in C# instead of JavaScript.
Razor
@page "/cart" <h1>Cart</h1><p>Items: @count</p> <button @onclick="Add">Add to cart</button> @code {    private int count = 0;     private void Add() => count++;}
Output
# CartItems: 0[button] Add to cartScreen: 3 clicks, still 0

66.2 Blazor Web App setup

  • dotnet new blazor -int Auto creates two projects: Shop (server) and Shop.Client (WebAssembly code).
  • AddRazorComponents + AddInteractiveServerComponents + AddInteractiveWebAssemblyComponents register both kinds of interactivity.
  • MapRazorComponents<App> turns pages into endpoints; AddAdditionalAssemblies adds the Client project's components.
C#
using Shop.Components;var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorComponents()    .AddInteractiveServerComponents()    .AddInteractiveWebAssemblyComponents(); var app = builder.Build();app.UseAntiforgery();app.MapStaticAssets();app.MapRazorComponents<App>()    .AddInteractiveServerRenderMode()    .AddInteractiveWebAssemblyRenderMode()    .AddAdditionalAssemblies(        typeof(Shop.Client._Imports).Assembly);app.Run();
Output
$ dotnet new blazor -n Shop -int AutoThe template "Blazor Web App" was created successfully.$ cd Shop/Shop$ dotnet run --urls http://localhost:5066info: Microsoft.Hosting.Lifetime[14]      Now listening on: http://localhost:5066info: Microsoft.Hosting.Lifetime[0]      Application started. Press Ctrl+C to shut down.

66.3 Fix: @rendermode InteractiveServer

  • One line: @rendermode InteractiveServer.
  • The component now runs on the server; the browser stays connected through a WebSocket called a circuit.
  • The server still prerenders the HTML (Items: 0) with a Blazor comment marker; blazor.web.js reads it and connects the circuit.
  • Checkpoint: refresh after 3 clicks shows Items: 0, because count lived in circuit memory and a refresh creates a new circuit (new id). Persist data in a database or storage.
Razor
@page "/cart"@rendermode InteractiveServer <h1>Cart</h1><p>Items: @count</p> <button @onclick="Add">Add to cart</button> @code {    private int count = 0;     private void Add() => count++;}
Output
# CartItems: 3[button] Add to cartConsole: WebSocket connected to ws://localhost:5066/_blazor?id=yoi8bCP0p9TE9E8BMLBprg
Output
# Static SSR (no render mode)$ curl -s localhost:5066/cart<h1>Cart</h1><p>Items: 0</p><button>Add to cart</button> # @rendermode InteractiveServer$ curl -s localhost:5066/cart<!--Blazor:{"type":"server",  "prerenderId":"f62d5535...", ...}--><h1>Cart</h1><p>Items: 0</p><button>Add to cart</button><!--Blazor:{"prerenderId":"f62d5535..."}-->
InteractiveServer: from request to click
  1. 1.GET /cart: server prerenders full HTML (Items: 0) with a Blazor marker type "server"

  2. 2.blazor.web.js reads the marker and opens a WebSocket circuit (/_blazor)

  3. 3.User clicks: the event goes over the circuit to the server

  4. 4.Server runs Add(), count++, re-renders and computes the UI diff

  5. 5.Diff is sent back over the circuit; browser shows Items: 3

Before the circuit connects, a click does nothing; on refresh a new circuit starts with fresh state

Output
# after 3 clicksItems: 3Console: WebSocket connected to ws://localhost:5066/_blazor?id=yoi8bCP0p9TE9E8BMLBprg# after refresh: new circuitItems: 0Console: WebSocket connected to ws://localhost:5066/_blazor?id=lcr7zOZJ6Gfo4rthbIBWNA

66.4 Four render modes

Render modeWhere code runsClicks work?Trade-off
Static SSR (default)Server, once per requestNoFastest, just HTML
InteractiveServerServer; UI updates over a SignalR circuitYesEvery user's circuit uses server memory; needs a live connection
InteractiveWebAssemblyBrowser on the .NET runtime (WASM)YesBig first download; code must be in the Client project
InteractiveAutoServer on first visit, WASM after downloadYesBest of both, more moving parts
  • InteractiveAuto components live in the Client project, because WebAssembly code must be downloaded by the browser.
  • On the first visit dotnet.native.wasm downloads in the background while clicks run over the server circuit.
Razor
@page "/offers"@rendermode InteractiveAuto <h1>Offers</h1><p>Likes: @likes</p><button @onclick="() => likes++">Like</button> @code {    private int likes = 0;}
Output
$ curl -s localhost:5066/offers<!--Blazor:{"type":"auto",  "prerenderId":"2b2e3657...", ...}--><h1>Offers</h1><p>Likes: 0</p># browser network, first visitGET /_framework/dotnet.native.a6k1euv12n.wasmGET /_blazor/negotiate?negotiateVersion=1WebSocket connected to ws://localhost:5066/_blazor# click Like: Likes: 1

66.5 Components: Parameter and EventCallback

  • ProductCard is a reusable component.
  • [Parameter] means the value comes from the parent; EditorRequired gives a build warning if the parent does not pass it.
  • EventCallback<Product> OnAdd lets the child send an event to the parent.
  • The parent page sets the render mode; child components run in the same mode.
  • A child should not change its own parameters; it tells the parent through the callback.
Razor
<div class="card">    <h3>@Product.Name</h3>    <p>Rs. @Product.Price</p>    <button @onclick="Add">Add</button></div> @code {    [Parameter, EditorRequired]    public Product Product { get; set; } = null!;     [Parameter]    public EventCallback<Product> OnAdd { get; set; }     Task Add() => OnAdd.InvokeAsync(Product);}
Razor
@page "/products"@rendermode InteractiveServer<h1>Products</h1><p>Cart: @cart.Count items</p> @foreach (var p in products){    <ProductCard Product="p" OnAdd="AddToCart" />} @code {    List<Product> cart = [];    List<Product> products = Catalog.All;    void AddToCart(Product p) => cart.Add(p);}
Output
# ProductsCart: 2 items## Mixer GrinderRs. 2499[button] Add## Steel BottleRs. 399[button] Add
Parent and child data flow
  1. 1.Products page loops over the catalog

  2. 2.Passes Product="p" (parameter) and OnAdd="AddToCart" (callback) to each ProductCard

  3. 3.User clicks Add in a card

  4. 4.Card calls OnAdd.InvokeAsync(Product)

  5. 5.Parent AddToCart adds to the cart and re-renders: Cart: 2 items

Data goes down through [Parameter], events go up through EventCallback

66.6 Forms: EditForm and validation

  • OrderForm uses the same data annotations: [Required], [RegularExpression] for a 6-digit pincode.
  • EditForm Model="order" OnValidSubmit="Place" runs Place only when the form is valid.
  • DataAnnotationsValidator switches the attributes on; InputText @bind-Value binds in both directions.
  • ValidationMessage shows the error under each field without a page reload.
C#
using System.ComponentModel.DataAnnotations; namespace Shop; public class OrderForm{    [Required]    public string? Name { get; set; }     [Required]    [RegularExpression(@"^\d{6}$",        ErrorMessage = "Pincode must be 6 digits")]    public string? Pincode { get; set; }}
Razor
@page "/checkout"@rendermode InteractiveServer<EditForm Model="order" OnValidSubmit="Place">  <DataAnnotationsValidator />  <InputText @bind-Value="order.Name" />  <ValidationMessage For="() => order.Name" />  <InputText @bind-Value="order.Pincode" />  <ValidationMessage For="() => order.Pincode" />  <button type="submit">Place order</button></EditForm><p>@status</p>@code {  OrderForm order = new(); string status = "";  void Place() => status = "Order placed!";}
Output
Input: (empty)The Name field is required.Input: (empty)The Pincode field is required.[button] Place order Input: AshaInput: 1100Pincode must be 6 digits[button] Place order Input: AshaInput: 110001[button] Place orderOrder placed!

66.7 Common mistakes

  • Expecting clicks to work without a render mode: the default is Static SSR.
  • EditForm on a Static SSR page without FormName: the POST gets 400 because the server does not know which form was submitted. Add FormName and [SupplyParameterFromForm].
  • Keeping important state only in an InteractiveServer component: it is lost on refresh.
  • Putting WebAssembly/Auto components in the server project instead of the Client project.
  • Thinking Blazor = only WebAssembly or no JavaScript: since .NET 8 one Blazor Web App template has Static SSR as default, and blazor.web.js plus JS interop are still used.
Razor
@* Wrong: Static SSR form without FormName -> 400 *@<EditForm Model="form" OnValidSubmit="Save">  <InputText @bind-Value="form.Name" />  <button type="submit">Send</button></EditForm> @* Right: FormName + SupplyParameterFromForm *@@page "/feedback"<EditForm Model="Form" OnValidSubmit="Save"          FormName="feedback">  <InputText @bind-Value="Form!.Name" />  <button type="submit">Send</button></EditForm><p>@status</p>@code {  [SupplyParameterFromForm]  FeedbackForm? Form { get; set; }  string status = "";  protected override void OnInitialized()      => Form ??= new();  void Save() => status = $"Thanks {Form!.Name}";}

66.8 Interview tips

  • Default in a Blazor Web App: Static SSR, HTML only, no interactivity.
  • InteractiveServer: code on the server, UI updates over a SignalR circuit (server memory per user).
  • InteractiveWebAssembly: code in the browser on the .NET runtime; Auto: server first, WASM once downloaded.
  • Components get data via [Parameter] and raise events via EventCallback.
  • Forms: EditForm + DataAnnotationsValidator; Static SSR forms need FormName.