向MVC中的视图添加特定的错误消息

sco*_*ker 2 validation asp.net-mvc razor

是否可以向视图中的字段添加特定的错误消息?目前,我已经在模型上进行了验证,以检查字段是否为空(ValidationMessageFor <>),并且我正在使用验证摘要来查找特定的错误。我想知道的是,为摘要创建的特定错误消息是否可以代替ValidationMessageFor <>?

模型:

 [Required]
 public string SchoolCode { get; set; }
Run Code Online (Sandbox Code Playgroud)

视图:

@Html.ValidationSummary("", new { @class = "text-danger" })
@Html.EditorFor(m => m.SchoolCode, new { htmlAttributes = new { @class = "form-control", @placeholder = "School Code" } })

@Html.ValidationMessageFor(model => model.SchoolCode, "", new { @class = "text-danger" })
Run Code Online (Sandbox Code Playgroud)

控制器:

var schoolExists = RepositoryHelper.GetSchoolByCode(model.SchoolCode);
if (schoolExists == null)
{
    ModelState.AddModelError(string.Empty, @"No school exists with this code");
    return View(model);
}
if (ModelState.IsValid)
{
    //do other stuff
}
Run Code Online (Sandbox Code Playgroud)

因此,如果模型状态无效,则返回模型错误,但是如果输入了错误的代码,则会在验证摘要中添加“此代码不存在任何学校”。我可以用学校代码摘要错误替换学校代码模型错误吗?

小智 5

您需要在AddModelError()方法中指定属性名称

ModelState.AddModelError("SchoolCode", "No school exists with this code");
Run Code Online (Sandbox Code Playgroud)

以便将其显示在由标识的占位符中 @Html.ValidationMessageFor(m => m.SchoolCode, ... })