【问题标题】:i want to apply validations on my form using blazor我想使用 blazor 在我的表单上应用验证
【发布时间】:2021-04-25 21:00:49
【问题描述】:
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.net
asp.net-core
blazor
【解决方案1】:
这是关于如何在 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