我有一些远程验证可用于客户端验证。其中两个几乎相同,但一个有效,另一个无效,断点永远不会被击中。
工作一:
查看:
@Html.EditorFor(model => model.ClassNumber, new { @id = "ClassNumber" })
@Html.ValidationMessageFor(model => model.ClassNumber)
型号:
[EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]
[Required(ErrorMessage = "Required")]
[Remote("CheckClassNumber", "Course", AdditionalFields = "Title", HttpMethod = "POST",
ErrorMessage = "Already Exists")]
[DataMemberAttribute()]
public global::System.Int32 ClassNumber
{
方法:
[HttpPost]
public JsonResult CheckClassNumber(int ClassNumber, int Title)
{
var course = db.Courses.Any(c => c.ClassNumber.Equals(ClassNumber) && c.Title.Equals(Title));
return Json(!course);
}
源代码:
<select class="chzn-select" data-placeholder=" -- Select Course -- " data-val="true" data-val-number="The field Title must be a number." data-val-required="Required" id="Title" name="Title">
<option value=""></option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
不工作
查看:
@Html.DropDownListFor(model => model.Student,
@ViewBag.StudentID as SelectList, "",
new { @class = "chzn-select", data_placeholder = " -- Select Student -- " })
@Html.ValidationMessageFor(model => model.Student)
型号:
[EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]
[Required(ErrorMessage = "Required")]
[Remote("CheckIfEnrolled", "Enrollment", AdditionalFields = "Course", HttpMethod = "POST",
ErrorMessage = "Already Enrolled")]
[DataMemberAttribute()]
public global::System.Int32 Student
{
方法:
[HttpPost]
public JsonResult CheckIfEnrolled(int Student, int Course)
{
var exists = db.Enrollments.Any(e => e.Course.Equals(Course) && e.Student.Equals(Student));
return Json(!exists);
}
源代码:
<select class="chzn-select" data-placeholder=" -- Select Student -- " data-val="true" data-val-number="The field Student must be a number." data-val-remote="Already Enrolled" data-val-remote-additionalfields="*.Student,*.Course" data-val-remote-url="/QIEducation/Enrollment/CheckIfEnrolled" data-val-required="Required" id="Student" name="Student">
<option value=""></option>
<option value="8">Option 1</option>
<option value="10">Option 2</option>
<option value="11">Option 3</option>
</select>
<span class="field-validation-valid" data-valmsg-for="Student" data-valmsg-replace="true"></span>
我已确保以正确的顺序加载脚本。正确键入其他字段。调试或查看源代码时不会出现错误。我环顾四周,已经实现了类似问题的解决方案。
答案 0 :(得分:0)
好的。事实证明,所选插件将select元素转换为隐藏元素。这意味着默认情况下验证不会检查它。我找到了一些适用于其他人的解决方案,但不适合我。我最终强迫改变验证。
<script type="text/javascript">
//Have to force a validation on change.
$('#Student').on('change', function () {
$('#Student').valid();
});
</script>
每次都有效,并且不会更改jquery文件中的默认值。