c# - 我想使用 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:'无法访问已处置的对象。”
解决方案
以下是有关如何在 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
推荐阅读
- sql - Osquery SQL - 搜索可执行文件
- c# - 如何在 Xamarin Android 中使用 ActivityResultContract?
- python - Google.colab,如何从 google.Drive 而不是本地章节导入多个图像?
- openssl - OpenSSL ECSA 签名和 Libsecp256k1
- charts - jsPDF - HTML 到 PDF 不显示 SVG(图表)
- pdf - 将 .Tif 文件转换为 PDF 的问题
- c++ - 在 C++ 中获取连接的设备名称
- cockroachdb - 对于 Cockroach DB,得到 'Caused by: org.postgresql.util.PSQLException: ERROR: root: memory budget exceeded
- pip - 尽管我刚刚安装了轮子,但它却不见了
- java - 适用于 android 的自定义 materila 日期范围选择器