How to update c# value in Blazor using javascript?

后端 未结 1 1401
旧时难觅i
旧时难觅i 2021-01-25 04:05

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

For example



        
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-25 04:41

    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:

    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

    0 讨论(0)
提交回复
热议问题