How can you read the current value of an input in an onkeypress method in Blazor? How can you read the current value of an input in an onkeypress method in Blazor? asp.net asp.net

How can you read the current value of an input in an onkeypress method in Blazor?


Unfortunately, you need oninput event to update the bound variable.

@value<input type="text" @bind="@value" @oninput="@(ui => { value = (string) ui.Value);})" />@functions {    string value;}


For people searching about this, you can implement this with .net core 3.1 to handle on keypress event on Blazor.

<input value="@stringValue" @oninput="(EventArgs) => {SetValue(EventArgs.Value.ToString()); DoSomethingElse();}"/>@code {    string stringValue = "";    private void SetValue(string Value)    {        stringValue = int.Parse(Value);    }}


"KeyboardEvent events just indicate what interaction the user had with a key on the keyboard at a low level". In order to access the text input, you should use the input event or change event instead. In Blazor, right now the input event is wrapped by the change event; that is, your code can access new values only after the input element has lost focus. What you should do, however, is define a property which is bound to the input element and can be accessed in your code for retrieval purposes:

protected string MyInput {get; set;}<input type="text" bind="@MyInput" /> 

The above binding is internally based on the change event, not the input event (again, right now it is not possible in Blazor)