Harry
Harry

Reputation: 4936

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.

Upvotes: 4

Views: 6183

Answers (2)

Ewerton
Ewerton

Reputation: 4523

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.

Upvotes: 2

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();
    }
}

Upvotes: 7

Related Questions