JavaScript Interoperability in Blazor
This blog is going to explain JavaScript Interoperability in Blazor. Sometimes it is necessary to use JavaScript in Blazor; you can not avoid that. To use the JavaScript in Blazor, you have to use the IJSRuntime instance via the dependency injection. The InvokeAsync method helps to call the JavaScript function.
Let's see how to use JavaScript in Blazor.
In Visual Studio -> Create a New Project -> Blazor App. Provide Project name and Location. Then click the Create button. It will display the Create a New Blazor app window. In there, select 'Blazor WebAssembly App';
Step 2: Create JavaScript File
In this step I have created a javascript file with the name
SampleJavaScript.js, under wwwroot -> Scripts folder. The following is
a code of simple javascript code for adding two integer numbers.
Step 3: JavaScript reference
In this step, I have added the JavaScript reference to the application. For
that, I included the javascript reference to the index.html page.
Step 4: Calculate Page
The following is a calculate page code. Here I have injected the
IJSRuntime instence using @inject directive. And added two
textbox to collect the input value and one button to display the calculated
value. Using InvokeVoidAsync()
method I have called the CalulateSum Javacript method and pass the input
value.
Output
The following is an output of the above code. Here you can see when the user
clicks on the sum button, it gives the result in JavaScript alert message.
I hope this helps you. Keep coding.
Comments
Post a Comment