如何使用JavaScript更新Blazor中的C#值? [英] How to update c# value in Blazor using javascript?
问题描述
我想知道是否可以使用Javascript
I am wondering is it possible to update C#
value in Blazor
using Javascript
例如
<input type="text" @bind="TestValue" >
<input type="button" value="Change value" onclick="ChangeValueFromJs()" >
@code
{
public string TestValue {get;set;} = "init value";
}
js
function ChangeValueFromJs()
{
}
是否可以更新TestValue
并将其成功绑定到使用js 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;
}
}
推荐答案
我尝试这样做,但是似乎没有用
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.
用C#委托包装onclick="ChangeValueFromJs()"
,该委托将通过此组件作为对js的引用:
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;
然后更改js以通过以下方式调用实例方法:
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');
});
}
最后,不要忘记添加StateHasChanged();
来通知组件
Finally, don't forget to add a StateHasChanged();
to notify the component
[JSInvokable("invokeFromJS")]
public Task ChangeValue()
{
TestValue = "New value";
StateHasChanged();
return Task.CompletedTask;
}
演示
这篇关于如何使用JavaScript更新Blazor中的C#值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!