Blazor preventDefault提交表单

时间:2020-04-12 05:28:21

标签: blazor blazor-client-side

在我的EditForm内,我想防止用户通过按下Enter键来提交表单。

我尝试了以下方法,但是没有用。

<button type="submit" @onkeypress:preventDefault>Save</button>

非常感谢!

4 个答案:

答案 0 :(得分:1)

这是一个工作代码示例,运行它并亲自查看按Enter键时未提交表单:

在第一个字段中输入一个值,然后在第二个字段中输入一个值,然后跳出,然后按Enter。现在查看“输出”窗口中打印的内容...您看到“提交...”字符串吗?我觉得不是。

<h1>My articles</h1>

<p>Leave me a comment</p>
<p>Note that the Save button is located outside of the EditForm component.</p>
<EditForm  Model="Model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />

    <div class="form-group">
        <label for="name">Name: </label>
        <InputText Id="name" Class="form-control" @bind-Value="@Model.Name"> 
                                                             </InputText>
        <ValidationMessage For="@(() => Model.Name)" />

    </div>
    <div class="form-group">
        <label for="body">Text: </label>
        <InputTextArea Id="body" Class="form-control" @bind- 
                                         Value="@Model.Text"></InputTextArea>
        <ValidationMessage For="@(() => Model.Text)" />
    </div>
    <p>
        <button type="submit" @onkeypress="@KeyHandler" 
                              @onkeypress:preventDefault>Submit</button>
    </p>
</EditForm>


@code
{

    private Comment Model = new Comment();

    private void HandleValidSubmit()
    {
        Console.WriteLine("Submit...");
    }

    void KeyHandler(KeyboardEventArgs args)
    {
        if (args.Key == "Enter")
        {
           return;
        }
        Console.WriteLine("KeyHandler...");

    }

}

答案 1 :(得分:1)

通过在EditForm中放置2个提交按钮,而第一个按钮处于禁用状态,我可以做到这一点。

<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<button type="submit">Save</button>

答案 2 :(得分:0)

尝试一下:

  <button type="submit" @onkeypress="@KeyHandler" 
                                  @onkeypress:preventDefault>Submit</button>

这:

    void KeyHandler(KeyboardEventArgs args)
    {
        if (args.Key == "Enter")
        {
            return;
        }


    }

答案 3 :(得分:0)

以下是JavaScript的答案,也很不愿意这样做:The Enter Key should Submit Forms, Stop Suppressing it

如果您仍然希望这样做:请确保您的表单具有多个输入和 no 提交按钮。

 <button type="button" @onclick="MySubmit">Save</button>

,然后使用EditContext或其他方法在MySubmit中处理您的验证。