我最近遇到了一个小问题。在创建新学生时,我必须测试 StudentNo
是否已在使用,它必须是唯一的。测试是在 Controller 中进行的。当 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
但我不知道如何添加。
部分 View :
<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"} } )
但这些都不起作用:/
最佳答案
您正在为 RadarNumberError
添加错误,但如果您希望突出显示该字段,则应该为 StudentNo
添加错误:
ModelState.AddModelError("StudentNo",
"This Student No. is already in use");
然后在您的 View 中,您只需渲染 StudentNo
的错误
<div class="editor-field">
@Html.EditorFor(model => model.StudentNo)
@Html.ValidationMessageFor(model => model.StudentNo)
</div>
关于c# - ValidationMessage 不会更改文本编辑器边框的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27036154/