【问题标题】:Blazor how to submit form without submit buttonBlazor 如何在没有提交按钮的情况下提交表单
【发布时间】:2021-12-20 16:48:57
【问题描述】:

在一个 blazor 项目中,我使用 EditformFluentvalidation 以及 Toolbelt.Blazor.HotKeys 作为快捷方式 (ctrl+s) 来提交表单 当我按 ctrl+s 时,会调用 Submit() 方法,但如果表单有错误,则不会显示错误。其实只调用了方法,没有调用提交表单。 你对这个问题有什么建议?

<EditForm Model="@model" OnValidSubmit="Submit">
            <FluentValidationValidator />
         ...
          <button type="submit" >save</button>
        </EditForm>

@code
{
 [Parameter] public CategoryInfo model { get; set; } = new();
 private async Task Submit()
    {
        var validator = new CategoryValidator();
        var result = validator.Validate(model);
        if (result.IsValid)
        {
            ...
        }
    }
}

【问题讨论】:

  • 请您发布组件的热键设置代码。我猜您已将热键链接到 Submit 方法,该方法实际上并未提交表单。
  • @MrCakaShaunCurtis 是的,我只是调用了提交方法,我尝试了_editContext.Validate(),但它总是返回true
  • 如果 _editContext.Validate() 返回 true,则模型验证。如果有未报告的错误,则说明您的 Fluent 验证代码有问题。

标签: .net-core blazor submit fluentvalidation blazor-editform


【解决方案1】:

这是一个有效的单页组件,它演示了在&lt;CTL&gt;S 上实现表单提交所需的代码。为简单起见,我使用了DataAnnotationsValidator。有内联的 cmets 来解释方法。

@page "/"
@implements IDisposable
@using Toolbelt.Blazor.HotKeys
@using System.ComponentModel.DataAnnotations;

<h3>EditForm</h3>

<EditForm EditContext="this._editContext" OnValidSubmit="ValidSubmitForm" OnInvalidSubmit="InvalidSubmitForm">
    <DataAnnotationsValidator />
    <div class="p-2">
        <span>Value (100-200):</span>
        <InputNumber @bind-Value="_model.Value" />
        <ValidationMessage For="() => _model.Value"/>
    </div>
    <div class="m-2 p-2">
        <button class="btn btn-success" type="submit">Submit</button>
    </div>
</EditForm>
<div class="m-2 p-2">
    <span>@message</span>
</div>
<div class="m-2 p-2">
    <button class="btn btn-danger" type="button" @onclick="SubmitFormExternally">Submit Form Externally</button>
</div>


@code {
    private string message;

    private Model _model = new Model();

    [Inject] private HotKeys hotKeys { get; set; }

    private HotKeysContext _hotKeysContext;

    EditContext _editContext;

    // Explicitly setup the Edit context so we have a reference to it
    protected override void OnInitialized()
    {
        _editContext = new EditContext(_model);
        _hotKeysContext = this.hotKeys.CreateContext()
         .Add(ModKeys.Ctrl, Keys.S, SubmitFormCtlS, "Submit form");

    }

    // Invalid handler
    private Task ValidSubmitForm()
    {
        message = $"Valid Form Submitted at :{DateTime.Now.ToLongTimeString()}";
        return Task.CompletedTask;
    }

    // Valid Handler
    private Task InvalidSubmitForm()
    {
        message = $" Invalid Form Submitted at :{DateTime.Now.ToLongTimeString()}";
        return Task.CompletedTask;
    }

    // Method to call from external button
    // Works and component updates as it's a Blazor Component event
    // emulates the private HandleSubmitAsync method in EditForm
    private async Task SubmitFormExternally()
    {
        if (_editContext.Validate())
            await this.ValidSubmitForm();
        else
            await this.InvalidSubmitForm();
    }

    // Method to call from shortcut key
    // The shortcut key mechanism does't wrap the call in a Blazor Component event
    // So we wrap the code within one
    // The code emulates the private HandleSubmitAsync method in EditForm
    private async Task SubmitFormCtlS()
    {
        var task = Task.CompletedTask;
        if (_editContext.Validate())
            task = this.ValidSubmitForm();
        else
            task = this.InvalidSubmitForm();
        this.StateHasChanged();
        if (!task.IsCompleted || task.IsCanceled)
        {
            await task;
            this.StateHasChanged();
        }
    }

    public void Dispose()
    {
        _hotKeysContext.Dispose();
    }

    // Quick Model Class
    public class Model
    {
        [Range(100, 200, ErrorMessage = "Must be between 100 and 200")]
        public int Value { get; set; } = 0;
    }
}

【讨论】:

  • 谢谢你,但我正在使用FluentValidationValidator :)
  • 同样的事情。将DataAnnotationsValidator 替换为FluentValidationValidator 并对您的模型进行验证。我使用了DataAnnotationsValidator,因为我可以将所有演示代码放在一起,并且在演示中使用非常简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 2011-04-02
  • 2015-07-30
  • 1970-01-01
相关资源
最近更新 更多