C# Blazor Basics Cheat Sheet
Covers Blazor component syntax, data binding, render modes (Server/WebAssembly/Auto), parameters, and component lifecycle for .NET 8+.
A Basic Component
`.razor` files mix HTML-like markup with C# in an `@code` block.
@page "/counter"<h1>Counter</h1><p>Current count: @count</p><button class="btn btn-primary" @onclick="Increment">Click me</button>@code { private int count = 0; private void Increment() { count++; }}
Render Modes (.NET 8+)
Choose per-component (or app-wide) whether it runs on the server, in WASM, or auto-switches.
@page "/dashboard"@rendermode InteractiveServer@* alternatives: InteractiveWebAssembly, InteractiveAuto, or omit for static SSR *@<h3>Live Dashboard</h3>@code { // InteractiveAuto: starts on Server for fast first load, // then switches to WASM once the .NET runtime downloads.}
Data Binding & Component Parameters
`@bind` for two-way binding, `[Parameter]` for parent-to-child data flow.
<!-- ChildComponent.razor --><input @bind="Name" @bind:event="oninput" /><p>Hello, @Name!</p>@code { [Parameter] public string Name { get; set; } = ""; [Parameter] public EventCallback<string> NameChanged { get; set; }}<!-- Parent.razor --><ChildComponent @bind-Name="parentName" />@code { private string parentName = "World";}
Lifecycle Methods & Injecting Services
`OnInitializedAsync` runs once; `@inject` pulls services from DI.
@page "/products"@inject IProductService ProductService@implements IDisposable<ul> @foreach (var p in products) { <li>@p.Name — @p.Price.ToString("C")</li> }</ul>@code { private List<Product> products = new(); protected override async Task OnInitializedAsync() { products = await ProductService.GetAllAsync(); } public void Dispose() { // cleanup subscriptions/timers here }}
Common Razor Directives
Directives you'll see at the top of most components.
- @page "/route"- makes the component routable at that URL
- @rendermode- sets Server/WebAssembly/Auto interactivity for the component
- @inject- injects a DI service as a property
- @bind- two-way data binding between an element and a field
- @onclick / @oninput- event binding to C# methods
- @code- block containing the component's C# members
- [Parameter]- marks a public property as settable from a parent component
Default new Blazor Web Apps to static server-side rendering and only opt individual components into `@rendermode InteractiveServer/WebAssembly` where you actually need interactivity — this keeps initial page loads fast and avoids shipping unnecessary WASM.
Explore Topics
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance