Telerik blogs
OpinionT2 Light_1200x303

Find out the benefits of Blazor over Angular, React and other JavaScript frameworks. Blazor enables sharing code across client- and server-side processes, server-side rendering functionality and more.

When building a single-page application, Angular or React are popular JavaScript frameworks to use. And up until now, the majority of client-side processes are written using JavaScript. However, there is an evolving framework that will allow you to write client-side processes using C#.

Blazor is a .NET framework for creating a single-page application that allows you to create your application using C#, Razor and HTML. The client-side of Blazor uses WebAssembly, which has been shipped with major browser engines, such as Internet Explorer, Chrome, Safari and Firefox. WebAssembly is an alternative to JavaScript in writing client-side code. And it can be converted using many different programming languages. In Blazor’s instance, it is converted using C#.

Why Use Blazor over a JavaScript Framework?

The integration of Blazor and WebAssembly gives you a different way of building a single-page application with the same results. So why should you choose Blazor over a JavaScript framework?

Choice Between One or Multiple Applications

At present, Blazor comes with two hosting models.

The first is Blazor Server. Blazor Server allows the application to be executed at server-side. Layout changes, event handling and JavaScript calls are done through a SignalR connection.

The other is Blazor WebAssembly. Blazor WebAssembly allows you to run the application client-side with the use of WebAssembly. If you need to integrate server-side functionality, you can either run it alongside Blazor Server, or you can use a separate API application.

Below is an example of running Blazor WebAssembly through a separate API application. When the page is initialized, it will display a list of technologies. These technologies are loaded through the API. Additionally, we have a text box and a button. When we enter some text and press the button, our entered text is sent to the API and returns an updated list of technologies.

@page "/"
@inject HttpClient httpClient
@using Newtonsoft.Json
<h1>Here is a list of .NET technologies</h1>
@if (Technologies != null && Technologies.Any())
{
    <ul>
        @foreach (var technology in Technologies)
        {
            <li>@technology</li>
        }
    </ul>
}
<input @bind="MessageInput" @bind:event="oninput" />
<button @onclick="MessageInputClick">Add Technology</button>

@code {
    public string MessageInput { get; set; }

    public List<string> Technologies { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Technologies = await httpClient.GetJsonAsync<List<string>>("https://localhost:44378/api/technology/getall");
    }

    public async Task MessageInputClick()
    {
        var postRequest = new Dictionary<string, string>();
        postRequest.Add("technology", MessageInput);

        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("POST"),
            RequestUri = new Uri("https://localhost:44378/api/technology/add"),
            Content = new StringContent(JsonConvert.SerializeObject(postRequest))
        };
        requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

        var response = await httpClient.SendAsync(requestMessage);
        var responseText = await response.Content.ReadAsStringAsync();

        Technologies = JsonConvert.DeserializeObject<List<string>>(responseText);

        MessageInput = string.Empty;
    }
}

Unlike Blazor, with a JavaScript framework, you always need to have a separate application if you wish to have server-side functionality.

Possible to Code in One Language

As Blazor WebAssembly allows you to write client-side code in C#, this means that any developers working on your application may only need to know one language.

This can have many benefits, particularly if you are responsible for running a Blazor project. Only needing to know one coding language means knowing the skills that you need your team members to be proficient in. It also makes it easier to assign roles to your team members, knowing there won't be a coding language barrier.

We are going to put some client-side coding in action. We display the current time on the page. When we press the button, the time is updated with the current time. All written in C#. No sign of JavaScript anywhere!

@page "/time"
<h3>Time</h3>
<p>The time is @CurrentTime.ToString("HH:mm:ss")</p>
<button @onclick="GetCurrentTime">Get Current Time</button>
@code {
    public virtual DateTime CurrentTime { get; set; }

    protected override void OnInitialized()
    {
        CurrentTime = DateTime.Now;
        base.OnInitialized();
    }

    public virtual void GetCurrentTime()
    {
        CurrentTime = DateTime.Now;
    }
}

To integrate this with a JavaScript library, you would have to build and integrate an API request to get the current server time. Thereafter, you would have to build the process of updating the time through the relevant JavaScript framework language. Of course, you could use JavaScript to get the time from the client’s machine, but if the time set on their machine is wrong, it will be displayed incorrectly on the page.

Sharing of Code Both Client-Side and Server-Side

Blazor allows you to share code both at client-side and server-side, meaning methods that share both hosting models only need to be written once. Subsequently, if you need to modify code shared by both, it only needs to be modified once and will be reflected on both hosting models.

The following example demonstrates this. We have created a new dependency-injection singleton interface called ITechnologyService that is inherited by TechnologyService. Inside this service is stored a list of technologies. When the Blazor application is loaded, the ITechnologyService service is injected into the page and displays a list of all the technologies. When we enter some text and press the button, the ITechnologyService service sends our inputted text through an Add method, and the list of displayed technologies is updated.

using System.Collections.Generic;

namespace BlazorShare.Data
{
    public partial class TechnologyService : ITechnologyService
    {
        protected virtual List<string> Technologies { get; }

        public TechnologyService()
        {
            Technologies = new List<string>();
            Technologies.Add("Blazor");
            Technologies.Add("MVC");
        }

        public virtual void AddTechnology(string technology)
        {
            Technologies.Add(technology);
        }

        public virtual List<string> GetAll()
        {
            return Technologies;
        }
    }

    public partial interface ITechnologyService
    {
        void AddTechnology(string technology);

        List<string> GetAll();
    }
}
@page "/"
@using BlazorShare.Data
@inject ITechnologyService technologyService
<h1>Here is a list of .NET technologies</h1>
@if (Technologies?.Any() ?? false)
{
    <ul>
        @foreach (var technology in Technologies)
        {
            <li>@technology</li>
        }
    </ul>
}
<input @bind="MessageInput" @bind:event="oninput" />
<button @onclick="MessageInputClick">Add Technology</button>

@code {
    public string MessageInput { get; set; }

    public List<string> Technologies { get; set; }

    protected override void OnInitialized()
    {
        Technologies = technologyService.GetAll();
    }

    public void MessageInputClick()
    {
        technologyService.AddTechnology(MessageInput);
        MessageInput = string.Empty;
    }
}

With JavaScript frameworks, if you need to use the TechnologyService service both client and server-side, you would need to build the service up both in JavaScript and in the relevant server-side coding language.

Server-Side Rendering

If your application integrates Blazor WebAssembly and Blazor Server, server-side rendering is included as standard.

Server-side rendering is important if you are building an application that you want crawled by search engines. Having server-side rendering allows a bot to crawl your application and read its contents without having to execute any JavaScript.

A good way of seeing if you have server-side rendering installed is to load your web page and then view the source. If the contents on the web page match the contents in the source code, it means that server-side rendering is enabled.

Take a look at this page that our Blazor application has rendered:

A simple page shows headline “Here is a list of .NET technologies” with bullet points “Blazor” and “MVC”. Then a blank form field has a button beside it labeled “Add technology”

If you were to view the source code of the page, the contents of this page will appear within the source code:

<div class="content px4">
    <h1>Here is a list of .NET technologies</h1>
    <ul>
        <li>Blazor</li>
        <li>MVC</li>
    </ul>
    <input />
    <button>Add Technology</button>
</div>

To include server-side rendering in a JavaScript framework, you may require additional software to be installed. This can present a challenge, as you may need your hosting provider to install the software for you, which they might not be willing to do.

An Enhancement for JavaScript

It’s worth noting that WebAssembly languages such as Blazor WebAssembly are more likely to enhance JavaScript rather than replace it in the near future. Blazor relies on JavaScript to power some of its features. For example, JavaScript is used to power the SignalR connection between the client and the server.

At present, Blazor WebAssembly is currently still in preview. But when it's fully released, it's likely to give stiff competition to the popular JavaScript frameworks that are available and give developers an interesting dilemma as to which framework to choose.

Looking for more on Blazor?

Dig deeper into Blazor and learn the fundamentals of Blazor Component construction with our free guide: Blazor Components: The Definitive Guide


David Grace
About the Author

David Grace

David has been a .NET software developer for over 10 years, specializing in web applications. He is proficient in ASP.NET and .NET Core and has used many of its packages such as MVC, Entity Framework and Blazor. He has also done extensive work with integrating databases with web applications, and has an in-depth knowledge of SQL Server. He also writes articles for his own blog, https://www.roundthecode.com, which is .NET related.

Related Posts

Comments

Comments are disabled in preview mode.