Blazor: Running C# in Frontend (cross-browser)

Blazor is a framework that allows you to code C# for frontend. Github page.

An experimental web UI framework using C#/Razor and HTML, running client-side via WebAssembly

The arrival of WebAssembly creates the possibility of building client-side web applications using languages and runtimes that are more typically used for native app development. Blazor runs .NET code in the browser via a small, portable .NET runtime called DotNetAnywhere (DNA) compiled to WebAssembly.

The programming model will be familiar to anyone who’s worked with Razor (the C#/HTML page format used by ASP.NET MVC and ASP.NET Pages).

Blazor makes your app compact and much faster since it is compiled into code the browser doesn’t have to parse.

It can run on older browsers (ex IE11) because it has polyfills.

The only note here is that it is very early. I mean, it is so early it can’t even be called alpha or anything. It is just an experiment at the moment. (Post written at 2017-08-12)

The prerequisite is .NET Core 2.0 preview 3 or later. Download SDK build 6764.

Basically from what I’ve tested you create .cshtml files and those are going to be your routes. It means if you create a file heroes.cshtml you can go and type /heroes in the url and this file will load.

Functions

You can define a functions section in your cshtml file where it will contain your C# code.

@functions {
    int currentCount;

    void IncrementCount()
    {
        currentCount++;
    }
}

Binding

You can bind click events like this

<button @onclick(IncrementCount)>Increment</button>

And for async click:

<button @onclickAsync(Model.OnSaveClick)>Save</button>

You can bind variables to inputs

<input @bind(Model.Name) class="form-control" />

Variables

You can display a variable value the same way you do in Razor, ex:

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

You can use conditions and other thinks just like Razor.

Model

You can have a .cshtml and .cs file (which means you don’t need the @functions section)

Examples

Videos/Podcasts/Posts

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s