我发现了 Foolproof 库,它看起来非常好,但我在让它工作时遇到了问题。
仅当下拉列表的选定值 = 7 时,我才想创建一个必填字段。
简单模型:
[RequiredIf("LeadSource_Id","7", ErrorMessage = "Campo obrigatório")]
public string SourceDescription { get; set; }
[Display(Name = "Origem")]
public virtual int LeadSource_Id { get; set; }
我在控制器中创建下拉菜单的方式:
ViewBag.LeadSource_Id = new SelectList(db.LeadSources.ToList(), "Id", "Name");
风景:
<div class="form-group">
@Html.LabelFor(model => model.LeadSource_Id, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("LeadSource_Id", null, htmlAttributes: new { @class = "form-control ld-lead-source" })
@Html.ValidationMessageFor(model => model.LeadSource_Id, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group collapse">
@Html.LabelFor(model => model.SourceDescription, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SourceDescription, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SourceDescription, "", new { @class = "text-danger" })
</div>
</div>
当我在选择值 7 时尝试查看验证是否有效时,我收到错误消息:
具有键“LeadSource_Id”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable<SelectListItem>”类型。
编辑:
我包括的库是:
<script src="~/Scripts/jquery/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery/jquery.validate.globalize.min.js"></script>
<script src="~/Scripts/mvcfoolproof.unobtrusive.min.js"></script>