我的模型类包含所需的查找值,这是一个基于查找的记录:
[Required]
[DisplayName("Business Unit")]
public string value { get; set; }
[Required] //not working on client side?
[DisplayName("Business Group")]
public int id_businessgroup { get; set; }
查看:
<div class="editor-label">
@Html.LabelFor(model => model.value)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.value)
@Html.ValidationMessageFor(model => model.value)
</div>
<div class="editor-label">
@Html.LabelFor(x=>x.BusinessGroup.value)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.id_businessgroup, new SelectList(ViewBag.BusinessGroups,"id","value"),"Please select group from list...")
@Html.ValidationMessageFor(x => x.id_businessgroup)
</div>
@section scripts{
@Html.Partial("ScriptUseChosen")
}
控制器:
public ActionResult Create()
{
ViewBag.BusinessGroups = DB.BusinessGroups.Where(x => x.is_active).OrderBy(x => x.value).ToList();
return View();
}
的Web.config:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive*"));
value
的验证在客户端完美运行,但它不适用于Chosen的下拉列表。可能是什么原因?
答案 0 :(得分:9)
jQuery Chosen通过隐藏原始选择(style="Display:none"
)来更新html。默认情况下,jquery.validate(1.9.0)忽略隐藏的元素。您可以使用
$.validator.setDefaults({
ignore: []
});
或
$('form').validate({
ignore: []
});
答案 1 :(得分:0)
确保选项标签未在下拉列表中呈现为从列表中选择组...,默认情况下它将被视为选定值,客户端验证将通过。
不要使用ViewBag进行数据绑定,而是尝试更改下面的模型,我测试它的工作正常,
[Required]
[DisplayName("Business Unit")]
public string value { get; set; }
[Required] //not working on client side?
[DisplayName("Business Group")]
public int id_businessgroup { get; set; }
public IEnumerable<SelectListItem> BussinessGroup { get; set; }
将数据绑定到控制器中的BussinessGroup,如
BussinessGroup = new List<SelectListItem>
{
new SelectListItem
{
Text = "A",
Value = "1"
},
new SelectListItem
{
Text = "B",
Value = "2"
}
}
最后在视图中将下拉列表绑定为
@Html.DropDownListFor(x=>x.id_businessgroup, Model.BussinessGroup, "Please select group from list...")
@Html.ValidationMessageFor(x=>x.id_businessgroup)
答案 2 :(得分:0)
我通过使用jquery的Select2插件找到了一个快速解决方法。我正在使用Chosen打开这个问题以解决问题。