Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify input while typing and make Blazor see the changes

I have an input element. I added some filtering and modifying the text while typing using JavaScript keydown and keypress events.

For example - when an input accepts upper case characters, when you press just "a" (no shift, no caps lock), you get "A".

This works, however input value binding doesn't work at all. I just call preventDefault() on the JS event and that's it, binding is broken.

I tried to dispatch the event myself. I dispatched newly created KeyboardEvent and CustomEvent with type "change". Nothing works. I can modify input value in JS event handler, I see the changes in browser, however my C# doesn't.

How can I make this work? Do I have to invoke C# manually to update the binding, or is there another way?

The code should work just on latest Chrome / Firefox browsers, older browsers may be unsupported.

like image 753
Harry Avatar asked Sep 01 '25 10:09

Harry


2 Answers

Why don't you do in in Blazor code? In you markdown:

<input type="text" @bind-value="MyParamenter" @bind-value:event="oninput" >

and in code

private string myParameter;

private string MyParameter
{
    get => myParameter;
    set
    {
        myParameter = value.ToUpper();
    }
}
like image 105
Дмитро Іванов Avatar answered Sep 04 '25 08:09

Дмитро Іванов


Maybe, this answers your question. In, short, when you want to handle the TextChanged event you could do something like this:

<MudTextField Label="Some Label Text"
              T="string"
              Value="person.FirstName"
              ValueChanged="(value) => person.FirstName = value.ToUpper()"
              Immediate="true" />

The "trick" is to split the @bind-value in two: Value and ValueChanged. Then in the ValueChanged you can do whatever you want with the power of C#.

Note that Blazor abstract the JS side from us, with some experience, I learned to stay away from JS side as much as possible when developing with Blazor and it saved me from a lot of headaches.

like image 32
Ewerton Avatar answered Sep 04 '25 10:09

Ewerton