Build your first web app with ASP.NET Core using Blazor

Try the counter

In the running app, navigate to the Counter page by clicking the Counter tab in the sidebar on the left. The following page should then be displayed:

The Counter page presents a Click me button to increment the count showed on the page.

Select the Click me button to increment the count without a page refresh. Incrementing a counter in a webpage normally requires writing JavaScript, but with Blazor you can use C#.

You can find the implementation of the Counter component at Counter.razor file located inside the Components/Pages directory.

Components/Pages/Counter.razor
@page "/counter"
@rendermode InteractiveServer

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content. The @rendermode directive enables interactive server rendering for the component, so that it can handle user interface events from the browser.

Each time the Click me button is selected:

  • The onclick event is fired.
  • The IncrementCount method is called.
  • The currentCount is incremented.
  • The component is rendered to show the updated count.
Continue