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.
[script.js]
function ChangeContentJS() {
DotNet.invokeMethodAsync('InvokeFromJsApp', "ChangeParaContentValue", "New Content");
}
[Index.razor]
@page "/"
@inject IJSRuntime JSRuntime
<h1>Change C# property value from JavaScript</h1>
<br />
<button @onclick='ButtonClickHandler'>Change Content - JS</button>
<br />
<p>@ParaContent</p>
@code {
public static string ParaContent = "Some Text Content";
public async Task ButtonClickHandler()
{
await JSRuntime.InvokeAsync<string>("ChangeContentJS");
}
[JSInvokable]
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 the 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
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.
Refer the script file in the HTML page
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 the 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.
need an explanation for this answer? contact us directly to get an explanation for this answer