问题
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