2

I started with Blazor today while already having some experience in web-dev. However it seems that isn't enough. I want to get the eventarguments of an onkeydown event, so I can check for an enter-key-press.

I already tried to use a function in my event to check the keypress in a separate function, and already tried directly inserting something into the onkeydown event but nothing worked.

The following is the event I want to get the keypress from.

<input onkeydown="" bind="@todo.Title" />
Tubif Fux
  • 146
  • 1
  • 12

1 Answers1

3

You need to use UIKeyboardEventArgs, something like passing event as argument in JavaScript.

<p id="p" onclick="doSomething(event);">

In Blazor you'll do it in the following way:

<input type="text" onkeypress="@(e => KeyWasPressed(e))" />

/* For .NET Core 3.0+ as per: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.web.keyboardeventargs?view=aspnetcore-3.1 */
@functions {
  private void KeyWasPressed(KeyboardEventArgs args)
  {
    if (args.Key == "r")
    {
      Console.WriteLine("R was pressed");
    }
  }
}

/* For old .NET Core versions */
@functions {
  private void KeyWasPressed(UIKeyboardEventArgs args)
  {
    if (args.Key == "r")
    {
      Console.WriteLine("R was pressed");
    }
  }
}

As @Bohring already mentioned in comments you'll still get the event arguments if you're writing onkeypress="@KeyWasPressed"

You can read more here about other event args: https://visualstudiomagazine.com/articles/2018/10/01/blazor-event-handling.aspx

Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
  • 1
    Ok this seems to work, thanks. The only problem I have now, is that I have to press Enter twice for it to execute my method. However if I unfocus and then click in the field again for pressing enter, it works the first time. – Tubif Fux May 15 '19 at 10:39
  • 2
    You can also just write `onkeypress="@KeyWasPressed"`. You still get the args. – Bohring May 15 '19 at 11:04
  • 2
    Okay solved it now. I now use onkeyup. Works like a charm. Thanks again Razvan – Tubif Fux May 15 '19 at 11:10
  • 2
    Im using dotnet 3.1.102 and I had to use KeyboardEventArgs as event argument type instead of UIKeyboardEventArgs – anhoppe Feb 23 '20 at 05:54