Live Chat Icon For mobile
Live Chat Icon

How do you update a C# value in Blazor using JavaScript?

We can change a C# property’s value in Blazor from JavaScript by invoking the method DotNet.invokeMethodAsync in the script file (.js file). It takes the parameters Assembly name (Application name), the method name (public static method), and method parameter where we can change the C# static parameter.

Refer to the following code snippet for more details.


function ChangeContentJS() {
    DotNet.invokeMethodAsync('InvokeFromJsApp', "ChangeParaContentValue", "New Content");

Refer the script file in the HTML page

 <script src="~/script.js"></script>

@page "/"

@inject IJSRuntime JSRuntime

<h1>Change C# property value from JavaScript</h1>
<br />
<button @onclick='ButtonClickHandler'>Change Content - JS</button>
<br />

@code {
    public static string ParaContent = "Some Text Content";
    public async Task ButtonClickHandler()
        await JSRuntime.InvokeAsync<string>("ChangeContentJS");

    public static void ChangeParaContentValue(string value)
        ParaContent = value;

In the previous example, we have changed the ParaContent C# field value from the JavaScript by calling the static method ChangeParaContentValue from JavaScript, along with the new value as one of parameters in invokeMethodAsync.

  • The C# method should be defined as static and it should have a JSInvokable attribute.
  • The arguments in the JavaScript method Dotnet.invokeMethodAsync should be
    • InvokeFromJsApp—AssemblyName.
    • ChangeParaContentValue—C# JSInvokable static method name.
    • “New Content”—method arguments.

You can download the reference sample here.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.