I am wondering is it possible to update C#
value in Blazor
using Javascript
For example
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.
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; }