Changing an Input value in Blazor by javascript doesn't change it's binded property value

笑着哭i 提交于 2020-04-16 03:38:25

问题


I'm building a website using app.net core 3.1 with blazor. In one of my components I have :

<input @bind="Message" type="text" id="input-message"/>

Message is just a string property.

and I have javascript:

document.getElementById('input-message').value = 'some text';

The problem is after running the above js, <input> value changes but Message value doesn't, and of course if I type or paste something inside <input> , Message value changes too.


回答1:


You shouldn't change the input value directly in javascript, what you should do is call a c# function that updates the value and then it will update the javascript.

Instead of doing

document.getElementById('input-message').value = 'some text';

You should do something like

DotNet.invokeMethodAsync('UpdateMessageValue', 'some text');

Where you have

public void UpdateMessageValue(string value){
    Message = value;
}

And because you are using bind in the input, the value of document.getElementById('input-message').value will be changed, and the value in the c# will also be changed.

This answer isn't complete, I'm passing you the idea on how to do it and not the correct code to solve your case, but if you want more information on how to do it, you can take a look at Call .NET methods from JavaScript functions in ASP.NET Core Blazor.




回答2:


Apparently changing <input> value or any other changes in DOM by javascript doesn't change State, so blazor won't re-render the component. Even calling StateHasChanged(); manually in your razor page won't work.

To get this done, you just have to trigger the same DOM events that occur if the user modifies the <input> normally, just like below:

var myElement = document.getElementById('input-message');
myElement.value = 'some text';
var event = new Event('change');
myElement.dispatchEvent(event);


来源:https://stackoverflow.com/questions/60929649/changing-an-input-value-in-blazor-by-javascript-doesnt-change-its-binded-prope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!