我最近遇到了一个小问题。在创建新学生时,我必须测试StudentNo
是否已被使用,它必须是唯一的。测试在控制器中。当StudentNo
已经在数据库中时,我添加了一个自定义错误:
Student studentToCheck = dbContext.Students
.FirstOrDefault(r => r.StudentNo == student.StudentNo);
if (studentToCheck != null)
{
ModelState.AddModelError("StudentNumberError",
"This Student No. is already in use");
}
虽然它工作正常,但即使我设置了CSS样式,它也没有设置TextBox
的边框:
.field-validation-error
{
color: Red;
}
.input-validation-error
{
border-color: Red;
}
我检查了结果网站的HTML,看起来我必须添加类input-validation-error
,但我不知道如何。
观点的一部分:
<div class="editor-label">
@Html.LabelFor(model => model.StudentNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StudentNo)
@Html.ValidationMessageFor(model => model.StudentNo)
@Html.ValidationMessage("StudentNumberError")
</div>
和类定义的一部分:
[Required, Display(Name = "Student No.")]
[RegularExpression("^(ST[0-9]{4})$",
ErrorMessage = "Student No. must be of the form: ST0000")]
public string StudentNo { get; set; }
我尝试手动添加课程:
@Html.ValidationMessage("StudentNumberError", new { {"class", "input-validation-error"} } )
或
@Html.ValidationMessage("StudentNumberError", new Dictionary<string, object>(){ {"class", "input-validation-error"} } )
但这些都不起作用:/
答案 0 :(得分:2)
您要为RadarNumberError
添加错误,但如果您希望突出显示该字段,则应将其添加到StudentNo
:
ModelState.AddModelError("StudentNo",
"This Student No. is already in use");
然后在您的视图中,您只需呈现StudentNo
<div class="editor-field">
@Html.EditorFor(model => model.StudentNo)
@Html.ValidationMessageFor(model => model.StudentNo)
</div>