写这个问题之前我看了很多文章。我正在学习 ASP.NET Core 8,数据验证/注释在我的练习中不起作用。当我调试表单的帖子发送的数据对象时,名称值显示为 null 但没有错误。请任何人都可以用他们的经验指导我。
以下是代码场景:
型号:
public class Employee
{
[Required] public int ID { get; set; }
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
public decimal Salary { get; set; }
}
视图 - 编辑视图用于
GET
@model Employee;
<div class="container">
<h1>Edit Form</h1>
<div class="row">
<div class="col-sm-8">
<form class="d-grid form-control-sm" asp-controller="Employee" asp-action="EditPost" method="post">
<div class="form-group row">
<label class="col-sm-2" asp-for="Name">Name</label>
<input type="text" class="col-sm-4" asp-for="Name"/>
<span asp-validation-for="Name" style="color:red"></span>
</div>
<input class="btn btn-primary col-sm-4" type="submit" name="Submit" value="Submit" />
</form>
</div>
</div>
</div>
控制器:
Edit
代表GET
,EditPost
代表POST
。 EditPost
没有自己的视图,它将修改后的数据传递给另一个操作项。
[HttpGet]
public IActionResult Edit(int id)
{
return View(emplist.Find(e => e.ID == id));
}
[HttpPost]
public IActionResult EditPost(Employee emp)
{
int index = emplist.FindIndex(e=>e.ID==emp.ID);
emplist.RemoveAt(index);
emplist.Insert(index, emp);
return View("Detail", emp);
}
提交表单按钮:
<input class="btn btn-primary col-sm-4" type="submit" name="Submit" value="Submit" />
Required
上的 Name
验证未显示。
我使用编辑表单将值编辑为空/空白。您首先看到的是,名称按其应有的方式填充:
现在我清空输入框并提交表单
接受空白名称:
您可以在
EditPost
操作方法中验证 ModelState 是否有错误
[HttpPost]
public IActionResult EditPost(Employee emp)
{
if (!ModelState.IsValid)
{
return View("Edit", model); // Returns the model back to Edit view with validation errors
}
int index = emplist.FindIndex(e=>e.ID==emp.ID);
emplist.RemoveAt(index);
emplist.Insert(index, emp);
return View("Detail", emp);
}
另请确保在
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
文件中添加行 _ViewImports.cshtml
。