首页 > 解决方案 > 我想使用 blazor 在我的表单上应用验证

问题描述

here is my code 
<form>
    <DataAnnotationsValidator/>
    <div class=" row">
        <div class=" col-md-8 ">
            <div class=" form-group">
                <label for="Name " class="control-label">Name</label>
                <input form=" Name " class=" form-control " @bind="@objEmp.Name" />
             <Validation Message For=" (() => objEmp.Name)"/>

            </div>
</form>

 public string Name { get; set; }
        [Required]

“System.ObjectDisposedException:'无法访问已处置的对象。”

标签: c#asp.netasp.net-coreblazor

解决方案


以下是有关如何在 blazor 中使用验证的示例:

模型:

public class ExampleModel
{
    [Required]
    public string Name { get; set; }
}

剃须刀组件:

@page "/"
@using BlazorApp1.Models;

<EditForm EditContext="@editContext" OnSubmit="@HandleSubmit">
    <DataAnnotationsValidator />
    <div class=" row">
        <div class=" col-md-8 ">
            <div class=" form-group">
                <label for="Name " class="control-label">Name</label>
                <input form=" Name " class=" form-control " @bind="@objEmp.Name" />
                <ValidationMessage For=" (() => objEmp.Name)" />

            </div>
            <button type="submit">Submit</button>
        </div>
        </div>
</EditForm>
@code{
    private ExampleModel objEmp = new ExampleModel();
    private EditContext editContext;

    protected override void OnInitialized()
    {
        editContext = new EditContext(objEmp);
    }
    private async Task HandleSubmit()
    {
        var isValid = editContext.Validate();
        if (isValid)
        {
            //do your stuff...
        }
        else
        {
            //do your stuff...
        }
      
    }
}

结果:

在此处输入图像描述

参考:

https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0


推荐阅读