Get started building .NET web apps that run in the browser with Blazor

Today we released our first public preview of Blazor, a new experimental .NET web framework using C#/Razor and HTML that runs in the browser with WebAssembly. Blazor enables full stack web development with the stability, consistency, and productivity of .NET. While this release is alpha quality and should not be used in production, the code for this release was written from the ground up with an eye towards building a production quality web UI framework.

In this release we've laid the ground work for the Blazor component model and added other foundational features, like routing, dependency injection, and JavaScript interop. We've also been working on the tooling experience so that you get great IntelliSense and completions in the Razor editor. Other features that have been demonstrated previously in prototype form, like live reload, debugging, and prerendering, have not been implemented yet, but are planned for future preview updates. Even so, there is plenty in this release for folks to start kicking the tires and giving feedback on the current direction. For additional details on what's included in this release and known issue please see the release notes.

Let's get started!

Help & feedback

Your feedback is especially important to us during this experimental phase for Blazor. If you run into issues or have questions while trying out Blazor please let us know!

  • File issues on GitHub for any problems you run into or to make suggestions for improvements.
  • Chat with us and the Blazor community on Gitter if you get stuck or to share how blazor is working for you.

Also, after you've tried out Blazor for a while please let us know what you think by taking our in-product survey. Just click the survey link shown on the app home page when running one of the Blazor project templates:

Blazor survey

Get started

To get setup with Blazor:

  1. Install the .NET Core 2.1 Preview 1 SDK.
  2. Install the latest preview of Visual Studio 2017 (15.7) with the ASP.NET and web development workload.
    • Note: You can install Visual Studio previews side-by-side with an existing Visual Studio installation without impacting your existing development environment.
  3. Install the ASP.NET Core Blazor Language Services extension from the Visual Studio Marketplace.

To create your first project from Visual Studio:

  1. Select File -> New Project -> Web -> ASP.NET Core Web Application
  2. Make sure .NET Core and ASP.NET Core 2.0 are selected at the top.
  3. Pick the Blazor template

    New Blazor app dialog

  4. Press Ctrl-F5 to run the app without the debugger. Running with the debugger (F5) is not supported at this time.

If you're not using Visual Studio you can install the Blazor templates from the command-line:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates
dotnet new blazor -o BlazorApp1
cd BlazorApp1
dotnet run

Congrats! You just ran your first Blazor app!

Building components

When you browse to the app, you'll see that it has three prebuilt pages: a home page, a counter page, and a fetch data page:

Blazor app home page

These three pages are implemented by the three Razor files in the Pages folder: Index.cshtml, Counter.cshtml, FetchData.cshtml. Each of these files implements a Blazor component. The home page only contains static markup, but the counter and fetch data pages contain C# logic that will get compiled and executed client-side in the browser.

The counter page has a button that increments a count each time you press it without a page refresh.

Blazor app home page

Normally this kind of client-side behavior would be handled in JavaScript, but here it's implemented in C# and .NET by the Counter component. Take a look at the implementation of the Counter component in the Counter.cshtml file:

@page "/counter"
<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button @onclick(IncrementCount)>Click me</button>

@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}

Each Razor (.cshtml) file defines a Blazor component. A Blazor component is a .NET class that defines a reusable piece of web UI. The UI for the Counter component is defined using normal HTML. Dynamic rendering logic (loops, conditionals, expressions, etc.) can be added using Razor syntax. The HTML markup and rendering logic are converted into a component class at build time. The name of the generated .NET class matches the name of the file.

Members of the component class are defined in a @functions block. In the @functions block you can specify component state (properties, fields) as well as methods for event handling or for defining other component logic. These members can then be used as part of the component's rendering logic and for handling events.

Note: Defining components in a single Razor file is typical, but in a future update you will also be able to define component logic in a code behind file.

Each time an event occurs on a component (like the onclick event in the Counter component), that component regenerates its render tree. Blazor will then compare the new render tree against the previous one and apply any modifications to the browser DOM.

Routing to components

The @page directive at the top of the Counter.cshtml file specifies that this component is a page to which requests can be routed. Specifically, the Counter component will handle requests sent to /counter. Without the @page directive the component would not handle any routed request, but it could still be used by other components.

Routing requests to specific components is handled by the Router component, which is used by the root App component in App.cshtml:

<!--
    Configuring this here is temporary. Later we'll move the app config
    into Program.cs, and it won't be necessary to specify AppAssembly.
-->
<Router AppAssembly=typeof(Program).Assembly />

Using components

Once you define a component it can be used to implement other components. For example, we can add a Counter component to the home page of the app, like this:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Counter />

If you build and run the app again (live reload coming soon!) you should now see a separate instance of the Counter component on the home page.

Blazor home page with counter

Component parameters

Components can also have parameters, which you define using public properties on the component class. Let's update the Counter component to have an IncrementAmount property that defaults to 1, but that we can change to something different.

@page "/counter"
<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button @onclick(IncrementCount)>Click me</button>

@functions {
    int currentCount = 0;

    public int IncrementAmount { get; set; } = 1;

    void IncrementCount()
    {
        currentCount += IncrementAmount;
    }
}

The component parameters can be set as attributes on the component tag. In the home page change the increment amount for the counter to 10.

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<Counter IncrementAmount="10" />

When you build and run the app the counter on the home page now increments by 10, while the counter page still increments by 1.

Blazor count by ten

Layouts

The layout for the app is specified using the @layout directive in _ViewImports.cshtml in the Pages folder.

@layout MainLayout

Layouts in Blazor are also also built as components. In our app the MainLayout component in Shared/MainLayout.cshtml defines the app layout.

@implements ILayoutComponent

<div class='container-fluid'>
    <div class='row'>
        <div class='col-sm-3'>
            <NavMenu />
        </div>
        <div class='col-sm-9'>
            @Body
        </div>
    </div>
</div>

@functions {
    public RenderFragment Body { get; set; }
}

Layout components implement ILayoutComponent. In Razor syntax interfaces can be implemented using the @implements directive. The Body property on the ILayoutComponent interface is used by the layout component to specify where the body content should be rendered. In our app the MainLayout component adds a NavMenu component and then renders the body in the main section of the page.

The NavMenu component is implemented in Shared/NavMenu.cshtml and creates a Bootstrap nav bar. The nav links are generated using the built-in NavLink component, which generates an anchor tag with an active CSS class if the current page matches the specified href.

The root component

The root component for the app is specified in the app's Program.Main entry point defined in Program.cs. This is also where you configure services with the service provider for the app.

class Program
{
    static void Main(string[] args)
    {
        var serviceProvider = new BrowserServiceProvider(configure =>
        {
            // Add any custom services here
        });

        new BrowserRenderer(serviceProvider).AddComponent<App>("app");
    }
}

The DOM element selector argument determines where the root component will get rendered. In our case, the app element in index.html is used.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>BlazorApp1</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>Loading...</app> <!--Root component goes here-->

    <script src="css/bootstrap/bootstrap-native.min.js"></script>
    <script type="blazor-boot"></script>
</body>
</html>

Bootstrapping the runtime

At build-time the blazor-boot script tag is replaced with a bootstrapping script that handles starting the .NET runtime and executing the app's entry point. You can see the updated script tag using the browser developer tools.

<script src="_framework/blazor.js" main="BlazorApp1.dll" entrypoint="BlazorApp1.Program::Main" references="Microsoft.AspNetCore.Blazor.dll,netstandard.dll,..."></script>

As part of the build Blazor will analyze which code paths are being used from the referenced assemblies and then remove unused assemblies and code.

Dependency injection

Services registered with the app's service provider are available to components via dependency injection. You can inject services into a component using constructor injection or using the @inject directive. The latter is how an HttpClient is injected into the FetchData component.

@page "/fetchdata"
@inject HttpClient Http

The FetchData component uses the injected HttpClient to retrieve some JSON from the server when the component is initialized.

@functions {
    WeatherForecast[] forecasts;

    protected override async Task OnInitAsync()
    {
        forecasts = await Http.GetJsonAsync<WeatherForecast[]>("/sample-data/weather.json");
    }

    class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF { get; set; }
        public string Summary { get; set; }
    }
}

The data is deserialized into the forecasts C# variable as an array of WeatherForecast objects and then used to render the weather table.

<table class='table'>
    <thead>
        <tr>
            <th>Date</th>
            <th>Temp. (C)</th>
            <th>Temp. (F)</th>
            <th>Summary</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var forecast in forecasts)
        {
            <tr>
                <td>@forecast.Date.ToShortDateString()</td>
                <td>@forecast.TemperatureC</td>
                <td>@forecast.TemperatureF</td>
                <td>@forecast.Summary</td>
            </tr>
        }
    </tbody>
</table>

Hosting with ASP.NET Core

The Blazor template creates a client-side web application that can be used with any back end, but by hosting your Blazor application with ASP.NET Core you can do full stack web development with .NET.

The "Blazor (ASP.NET Core Hosted)" project template creates a solution with three projects for you: 1. a Blazor client project, 2. an ASP.NET Core server project, and 3. a shared .NET Standard class library project.

To host the Blazor app in ASP.NET Core the server project has a reference to the client project. Blazor-specific middleware makes the Blazor client app available to browsers.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseResponseCompression();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc(routes =>
    {
        routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");
    });

    app.UseBlazor<Client.Program>();
}

In the standalone Blazor app the weather forecast data was a static JSON file, but in the hosted project the SampleDataController provides the weather data Using ASP.NET Core.

The shared class library project is referenced by both the Blazor client project and the ASP.NET Core server project, so that code can be shared between the two projects. This is a great place to put your domain types. For example, the WeatherForecast class is used by the Web API in the ASP.NET Core project for serialization and in the Blazor project for deserialization.

Build a todo list

Let's add a new page to our app that implements a simple todo list. Add a Pages/Todo.cshtml file to the project. We don't have a Blazor component item template in Visual Studio quite yet, but you can use the Razor View item template as a substitute. Replace the content of the file with some initial markup:

@page "/todo"

<h1>Todo</h1>

Now add the todo list page to the nav bar. Update Shared/Navbar.cshtml to add a nav link for the todo list.

<li>
    <NavLink href="/todo">
        <span class='glyphicon glyphicon-th-list'></span> Todo
    </NavLink>
</li>

Build and run the app. You should now see the new todo page.

Blazor todo start

Add a class to represent your todo items.

public class TodoItem
{
    public string Title { get; set; }
    public bool IsDone { get; set; }
}

The Todo component will maintain the state of the todo list. In the Todo component add a field for the todos in a @functions block and a foreach loop to render them.

@page "/todo"

<h1>Todo</h1>

<ul>
    @foreach (var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>

@functions {
    IList<TodoItem> todos = new List<TodoItem>();
}

Now we need some UI for adding todos to the list. Add a text input and a button at the bottom of the list.

@page "/todo"

<h1>Todo</h1>

<ul>
    @foreach (var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>

<input placeholder="Something todo" />
<button>Add todo</button>

@functions {
    IList<TodoItem> todos = new List<TodoItem>();
}

Nothing happens yet when we click the "Add todo" button, because we haven't wired up an event handler. Add an AddTodo method to the Todo component and register it for button click using the @onclick attribute.

@page "/todo"

<h1>Todo</h1>

<ul>
    @foreach (var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>

<input placeholder="Something todo" />
<button @onclick(AddTodo)>Add todo</button>

@functions {
    IList<TodoItem> todos = new List<TodoItem>();

    void AddTodo()
    {
        // Todo: Add the todo
    }
}

The AddTodo method will now get called every time the button is clicked. To get the title of the new todo item add a newTodo string field and bind it to the value of the text input using the @bind attribute. This sets up a two-way bind. We can now update the AddTodo method to add the TodoItem with the specified title to the list. Don't forget to clear the value of the text input by setting newTodo to an empty string.

@page "/todo"

<h1>Todo</h1>

<ul>
    @foreach (var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>

<input placeholder="Something todo" @bind(newTodo) />
<button @onclick(AddTodo)>Add todo</button>

@functions {
    IList<TodoItem> todos = new List<TodoItem>();
    string newTodo;

    void AddTodo()
    {
        if (!String.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem { Title = newTodo });
            newTodo = "";
        }
    }
}

Lastly, what's a todo list without check boxes? And while we're at it we can make the title text for each todo item editable as well. Add a checkbox input and text input for each todo item and bind their values to the Title and IsDone properties respectively. To verify that these values are being bound, add a count in the header that shows the number of todo items that are not yet done.

@page "/todo"

<h1>Todo (@todos.Where(todo => !todo.IsDone).Count())</h1>

<ul>
    @foreach (var todo in todos)
    {
        <li>
            <input type="checkbox" @bind(todo.IsDone) />
            <input @bind(todo.Title) />
        </li>
    }
</ul>

<input placeholder="Something todo" @bind(newTodo) />
<button @onclick(AddTodo)>Add todo</button>

@functions {
    IList<TodoItem> todos = new List<TodoItem>();
    string newTodo;

    void AddTodo()
    {
        if (!String.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem { Title = newTodo });
            newTodo = "";
        }
    }
}

Build and run the app and try adding some todo items.

Finished Blazor todo list

Publishing and deployment

Now let's publish our Blazor app to Azure. Right click on the project and select Publish (if you're using the ASP.NET Core hosted template make sure you publish the server project). In the "Pick a publish target" dialog select "App Service" and "Create New".

Pick a publish target

In the "Create App Service" dialog pick a name for the application and select the subscription, resource group, and hosting plan that you want to use. Tap "Create" to create the app service and publish the app.

Create app service

Your app should now be running in Azure.

Blazor on Azure

You can mark that todo item to build your first Blazor app as done! Nice job!

For a more involved Blazor sample app check out the Flight Finder sample on GitHub.

Blazor Flight Finder

Summary

This is the first preview release of Blazor. Already you can get started building component-based web apps that run in the browser with .NET. We invite you to try out Blazor today and let us know what you think about the experience so far. You can file issues on Github, take our in-product survey, and chat with us on Gitter. But this is just the beginning! We have many new features and improvements planned for future updates. We hope you enjoy trying out this initial release and we look forward to sharing new improvements with you in the near future.