Skip to content Skip to sidebar Skip to footer

Changing An Input Value In Blazor By Javascript Doesn't Change It's Binded Property Value

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

Solution 1:

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';
varevent = new Event('change');
myElement.dispatchEvent(event);

Solution 2:

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

publicvoidUpdateMessageValue(stringvalue){
    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.

Post a Comment for "Changing An Input Value In Blazor By Javascript Doesn't Change It's Binded Property Value"