Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - Blazor two-way bind not detected when is updated from JS

I have a simple two-way binded component:

<input type="text"  id="myInput" bind="@MyVar" />
...
@functions {
    private string MyVar { get; set; } = "foo";

All runs fine when I write text on input box. But, if input value is set from javascript then blazor is no able to detect the changed value.

document.getElementById('myInput').value='Random Value';

I tried to raise some events on element like 'key pressed' and so but the private var MyVar has no changes on blazor client side.

I would like to send back to blazor some values from client, I guess changing value of a hidden input may be solution, but not working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you enter a value into the input box an event is raised, and thus Blazor knows of that, and it updates the property ( MyVar ) to which the input box is bound (this is slso how Angular two-way binding works), but when you change the value of the input box from JavaScript, Blazor has no way to know about this occurrence.

But, hey, why would you do such a thing ?

To send data from JavaScript to Blazor, you shoud define a public and static method in Blazor, annotated with the attibute [JSInvokable], and a JavaScript function that calls this method:

[JSInvokable]
public static Task SendMessageAsync(string message)
{
    // Do something with message
}

DotNet.invokeMethodAsync(assemblyName, 'SendMessageAsync', "Hello Blazor");

Read more here: https://blogs.msdn.microsoft.com/webdev/2018/07/25/blazor-0-5-0-experimental-release-now-available/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...