...

/

Calling C# Code From JavaScript

Calling C# Code From JavaScript

Learn to call C# code from 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>
Blazor project setup with JavaScript interop

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 Pages folder. We do this on line 27 with the IncrementNumber method that returns an int. We then mark the UpdateIncrement method by adding the same attribute on line 34.

Note: ...