【发布时间】:2026-01-10 08:30:01
【问题描述】:
是否可以向视图中的字段添加特定的错误消息? 目前我对模型进行了验证以检查字段是否为空(ValidationMessageFor),并且我正在使用验证摘要来处理特定错误。 我想知道为摘要创建的特定错误消息是否可以替换 ValidationMessageFor?
型号:
[Required]
public string SchoolCode { get; set; }
查看:
@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" })
控制器:
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
}
因此,如果模型状态无效,它会返回模型错误,但如果输入了不正确的代码,它会在验证摘要中添加“No school exists with this code”。可以用学校代码汇总错误代替学校代码模型错误吗?
【问题讨论】:
-
以后请格式化您的代码以便更好地阅读。
标签: asp.net-mvc validation razor