Calling C# Code From JavaScript
Explore how to call C# methods from JavaScript in Blazor applications. Understand the use of the JSInvokable attribute for static and instance methods, manage object references with DotNetObjectReference, and invoke methods via IJSRuntime. Gain practical knowledge to enhance interactivity between C# and JavaScript in Blazor.
JavaScript interop in Blazor works in two ways: As well as being able to call JavaScript functions from Blazor code, we can call C# methods from JavaScript code.
In this lesson, we will learn how to call C# Blazor methods from JavaScript. Since there are multiple ways of doing so, we will use the following project setup. In this project, we’ve modified the standard Blazor WebAssembly template. In the Counter Razor component, instead of performing a simple increment when the user clicks a button, we do this via a chain of JavaScript interop calls to demonstrate how they work.
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
Making C# methods invocable from JavaScript
To make a C# method in a Razor component invocable from JavaScript, we must add the [JSInvokable] attribute. We've added some examples of this in the Counter.razor file in the ...