我在asp.net mvc razor视图中有以下部分,它生成一个复选框列表。 我希望能够验证至少有一个被勾选。
<div class="form-group">
<div class="row col-md-12 ">
<div class=" col-md-11 col-md-offset-1">
@for (int i = 0; i < Model.PeronsExpList.Count(); i++)
{
<div class="col-md-12">
@Html.HiddenFor(x => Model.PeronsExpList[i].PeronExpId)
@Html.CheckBoxFor(x => Model.PeronsExpList[i].selected, new { @class = "{peopleExp: true}", @name = "peopleExp"})
@Html.DisplayFor(x => Model.PeronsExpList[i].PeronName, Model.PeronsExpList[i].PeronName)
</div>
}
</div>
</div>
</div>
我有以下javascript来提供此功能:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$.validator.addMethod("peopleExp", function (value, elem, param) {
if ($(".peopleExp:checkbox:checked").length > 0) {
return true;
} else {
return false;
}
}, "You must select at least one!");
</script>
}
然而,当我测试它时,即使没有勾选,我也可以提交te页面。
答案 0 :(得分:0)
感谢@AmitSingh链接资源以解决此问题
查看修改为:
<div class="form-group">
<div class="row col-md-12 ">
<div class=" col-md-11 col-md-offset-1">
@for (int i = 0; i < Model.PeronsExpList.Count(); i++)
{
<div class="col-md-12">
@Html.HiddenFor(x => Model.PeronsExpList[i].PeronExpId)
@Html.CheckBoxFor(x => Model.PeronsExpList[i].selected, new { @type = "checkbox"})
@Html.DisplayFor(x => Model.PeronsExpList[i].PeronName, Model.PeronsExpList[i].PeronName)
</div>
}
</div>
</div>
</div>
Sumit按钮更改为:
<input type="submit" name="Submit" value="Add Control Measure" class="btn btn-primary" disabled />
Javascript修改为:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.click(function () {
submitButt.attr("disabled", !checkboxes.is(":checked"));
})
</script>
}