How to update c# value in Blazor using javascript?

可紊 提交于 2020-08-09 10:19:13

问题


I am wondering is it possible to update C# value in Blazor using Javascript

For example

<input type="text" @bind="TestValue" >
<input type="button" value="Change value" onclick="ChangeValueFromJs()" >

@code
{
public string TestValue {get;set;} = "init value";
}

js

function ChangeValueFromJs()
{

}

Is there a way to update TestValue and successfully bind it to text input using js ChangeValueFromJs?

I tried doing this, but it didn't seem to work

function ChangeValueFromJs()
{
     DotNet.invokeMethodAsync("BlazorApp", "invokeFromJS", "ChangeValue");
}

@code
{
    [JSInvokable("invokeFromJS")]
    public static Task ChangeValue()
    {
          TestValue = "New value";
          return null;
    }
}

回答1:


I tried doing this, but it didn't seem to work

You're almost there. In order to invoke an instance method, you need to pass the instance reference to Javascript.

How-to

Wrap the onclick="ChangeValueFromJs()" with a C# delegate that will pass this component as a reference to js:

<input type="button" value="Change value" 
    onclick="ChangeValueFromJs()"
    @onclick='async (e) => await jsRuntime.InvokeAsync("ChangeValueFromJs", DotNetObjectReference.Create(this))' 
/gt;

And then change the js to invoke the instance method in following way:

function ChangeValueFromJs(wrapper)
{
    return wrapper.invokeMethodAsync("invokeFromJS")
        .then(_=>{
            console.log('state has changed');
        });
}

Finally, don't forget to add a StateHasChanged(); to notify the component

[JSInvokable("invokeFromJS")]
public Task ChangeValue()
{
    TestValue = "New value";
    StateHasChanged(); 
    return Task.CompletedTask;
}

Demo



来源:https://stackoverflow.com/questions/58803207/how-to-update-c-sharp-value-in-blazor-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!