Blazor  

Blazor Cheatsheet – A Beginner-Friendly Guide

Introduction

Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# instead of JavaScript. It is part of the .NET ecosystem, making it possible to run C# code directly in the browser with the help of WebAssembly, or on the server with a real-time connection. This cheatsheet is a quick guide to the most critical Blazor features, syntax, and usage examples.

Blazor Hosting Models

Blazor Server

  • Runs on the server.

  • Uses SignalR to update UI.

  • Small download size.

  • Example

          
            @page "/counter"
    <h3>Counter</h3>
    <p>Count: @count</p>
    <button @onclick="Increment">Click</button>
    
    @code {
        private int count = 0;
        private void Increment() => count++;
    }
          
        
  • Important: Faster load, but requires a constant connection.

Blazor WebAssembly

  • Runs in the browser.

  • Uses WebAssembly to execute .NET code.

  • Larger download size.

  • Important: Works offline after first load.

Components

  • Small building blocks of UI.

  • Written in .razor files.

  • Example

          
            @code {
        [Parameter] public string Title { get; set; }
    }
    
    <h3>@Title</h3>
          
        
  • Important: Use [Parameter] for parent-to-child data.

Data Binding

1. One-way binding

  
    <p>Hello, @name</p>
@code {
    string name = "Rinki";
}
  

Data flows from code to UI.

2. Two-way binding

  
    <input @bind="name" />
<p>@name</p>

@code {
    string name = "Rinki";
}
  

Data syncs between UI and code.

Event Handling

  • Use @on... attributes.

  • Example

          
            <button @onclick="ShowMessage">Click</button>
    
    @code {
        void ShowMessage() => Console.WriteLine("Clicked!");
    }
          
        

Lifecycle Methods

  • Special methods that control component behavior.

  • Common ones

          
            protected override void OnInitialized() { }
    protected override void OnParametersSet() { }
    protected override async Task OnAfterRenderAsync(bool firstRender) { }
          
        
  • Important

    • OnInitialized: Runs when the component is created.

    • OnParametersSet: Runs when the parent sends new data.

    • OnAfterRenderAsync: Runs after rendering UI.

Dependency Injection

  • Services can be injected into components.

  • Example

          
            @inject HttpClient Http
    
    <button @onclick="GetData">Fetch Data</button>
    
    @code {
        string data;
        async Task GetData() {
            data = await Http.GetStringAsync("https://api.example.com/data");
        }
    }
          
        
  • Important: Register services in the Program.cs file.

Routing

  • Define a route with @page.

  • Example

          
            @page "/about"
    <h3>About Page</h3>
          
        
  • For navigation

          
            <NavLink href="/about">Go to About</NavLink>
          
        

Forms and Validation

  • Use EditForm with models.

  • Example

          
            @page "/form"
    <EditForm Model="user" OnValidSubmit="HandleValidSubmit">
        <InputText @bind-Value="user.Name" />
        <ValidationMessage For="@(() => user.Name)" />
        <button type="submit">Submit</button>
    </EditForm>
    
    @code {
        User user = new();
        void HandleValidSubmit() => Console.WriteLine("Submitted!");
        class User { public string Name { get; set; } }
    }
          
        

State Management

  1. Local state (inside component): Use fields/properties.

  2. App-wide state: Use services registered as Scoped.

JavaScript Interop

  • Call JS from C# or vice versa.

  • Example

          
            @inject IJSRuntime JS
    
    <button @onclick="CallJS">Run JS</button>
    
    @code {
        async Task CallJS() {
            await JS.InvokeVoidAsync("alert", "Hello from Blazor");
        }
    }
          
        

Reusable Layouts

  • Use MainLayout.razor.

  • Example

          
            @inherits LayoutComponentBase
    <div class="page">
        <div class="sidebar">Menu</div>
        <div class="content">@Body</div>
    </div>
          
        
  • Important: @Body This is where the child page renders.

Error Handling

  • Use try-catch in methods.

  • Example

          
            try {
        await Http.GetStringAsync("bad-url");
    } catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }
          
        

Conclusion

Blazor empowers developers to create modern web applications using C# instead of JavaScript. With features such as components, data binding, routing, forms, dependency injection, and JavaScript interop, Blazor brings the entire .NET ecosystem to web development. This cheatsheet covers the most valuable concepts for getting started and building scalable apps faster.