Note: Here is my GitHub Repository and my Azure hosted site displaying the code below.
A big selling point behind Blazor is the ability write code in C# over Javascript. While it’s a great feature to seamlessly develop web applications in C#, the Blazor team had the foresight to still include Javascript support. This is an important asset as Javascript is the most widely used programming language in the world. There are a wide array of resources, libraries, and tutorials for Javascript, and all major browsers support javascript.
Despite Blazor supporting Javascript, it has a few more steps than normal to use it. Normal being that javascript can be added directly into an html file. We will go through how to call Javascript functions and where to reference those scripts in Blazor.
Above is the Index.razor file where Javascript is being called within a Blazor app. We’ll dive into more details below.
In order to use Javascript, an instance of IJSRuntime needs to be injected.
@inject IJSRuntime iJSRuntime;
The IJSRuntime instance is how javascript functions will be called in a Blazor page. This will make more sense as we see it in use.
<button class="btn btn-primary" @onclick="AlertBox">Alert Window!</button>
Above is a relatively standard html button, except for the @onclick, which is an event handler. There are several of these (@onclick, @onchange etc…) and it’s a great way to call certain methods if an event occurs. In this case, the AlertBox function will be called when the button is clicked. If there are no parameters for your method, you can just use the name of the method. For methods with parameters, you’ll have to use a lambda function, which will be covered later.
private void AlertBox()
{
iJSRuntime.InvokeVoidAsync("alert", "JS Alert box appeared!");
}
Here is where IJSRuntime comes back into play. You use the instance to call the InvokeVoidAsync method with two parameters. The first is the name of the function, and any subsequent ones will be parameters for the Javascript function. The statement above is equivalent to the Javascript statement below.
alert(“JS Alert box appeared!”);
Next, we’ll be creating a new javascript function and calling it in the Blazor page.
<input type="text" id="text_input" style="margin: 5px;" />
<br />
<button class="btn btn-primary" @onclick="PrintTextBox">Print Text Box</button>
Now we have created an input text box with an id and a button tag that calls PrintTextBox.
private void PrintTextBox()
{
iJSRuntime.InvokeVoidAsync("PrintTextBox", "text_input");
}
Similar to before, we’re calling a Javascript function named PrintTextBox with a parameter of text_input. Let’s look at the function.
The function will find the element passed as a parameter and print whatever is within the input text box to the alert window. The last step is to add the script source to the Blazor app. You can use Blazor as a server app (Pages/_Host.cshtml) or a WebAssembly app (wwwroot/index.html), and the corresponding locations are where you should add the script source.
Below is an example of adding the reference to a Blazor Server app. I’d also suggest saving any Javascript files in wwwroot/js.
Lines 34-36 have the syntax for adding a script source.
The final function we’ll be going over is simple fahrenheit to celsius converter. In the input number element, you’ll see that we bind the value to fahrenheit, and that value is updated ‘oninput’.
Fahrenheit: <input type="number" min="-1000" style="margin: 5px;" @bind-value="fahrenheit" @bind-value:event="oninput" />
<button class="btn btn-primary" @onclick="() => ConvertToCelsius(fahrenheit)">Convert to Celsius</button>
Fahrenheit and celsius are initialized in the code section at the bottom of the Blazor page. This method is a bit different as it’s asynchronous. Without delving into deep detail, asynchronous allows for a task (thread) to execute concurrently with other tasks in the program.
@code {
float celsius = 0.0f;
float fahrenheit = 0.0f;
….
private async void ConvertToCelsius(float far)
{
celsius = await iJSRuntime.InvokeAsync<float>("ConvertToCelsius", fahrenheit);
await iJSRuntime.InvokeVoidAsync("alert", fahrenheit + "F is " + celsius + "C");
}
}
Here, celsius is being assigned a value from the Javascript function. You’ll notice that IJSRuntime is calling InvokeAsync<float>, which means that we are calling a function that will return a variable of type float. Let’s take a quick look at the Javascript function.
This is a very basic function that is only being utilized to show how returning a variable works. Make sure to add a reference to any scripts that you will be using. The final statement just prints the fahrenheit to celsius values to the alert window.
Displayed throughout this article were the basics of implementing Javascript into Blazor pages. While the purpose of Blazor is full C# functionality, you’d be remiss to exclude Javascript from your projects. You can also use Javascript inside C# classes and call C# functions inside Javascript code, however these are slightly more advanced and will be discussed in a different article.
I hope the information provided in this article helps add more functionality and a greater user experience to your projects!
