How to programmatically submit a Blazor form?

Viewed 5315

Having a Blazor EditForm and a contained InputTextArea (i.e. a multiline text box), I do want to validate and submit the form, when the user presses Ctrl+Enter, just as if he would click the submit button.

I've successfully got the keyboard handler connected like this:

<EditForm Model="@myModel" Format="g" OnValidSubmit="@Store" @ref="_editForm">
    <InputTextArea 
        onkeypress="@(async e => await myKeyPress(e))"
        @bind-Value="myModel.Foo" />
    <button type="submit">Store it</button>
</EditForm>

With this code behind:

private EditForm _editForm;

private async Task myKeyPress(KeyboardEventArgs key)
{
    if (key.CtrlKey && key.Code == @"Enter")
    {
        _editForm.??? // What to call here?
    }
}

Unfortunately, I see no method in the EditForm class that I could call to submit and validate the form, as if the user would click the submit button.

I've looked at this and this SO question with no success.

My question

How to programmatically submit and validate a Blazor form?

1 Answers
<EditForm Context=MyCurrentEditContext>
  <InputTextArea 
        onkeypress="@(async e => await myKeyPress(MyCurrentEditContext, e))"
        @bind-Value="myModel.Foo" />
    <button type="submit">Store it</button>
</EditForm>

@code
{
private async Task myKeyPress(EditContext editContext, KeyboardEventArgs key)
{
    if (key.CtrlKey && key.Code == @"Enter")
    {
        if (editContext.Validate())
        {
          ... Do stuff if valid
        }
    }
}
}
Related