如何根据MVC中的下拉选择设置validation?

这是我的查看代码:

@Html.LabelFor(model => model.device.HasAMC, htmlAttributes: new { @class = "control-label col-lg-4" }) @Html.EditorFor(model => model.device.HasAMC, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model => model.device.AMCExpiredDate, htmlAttributes: new { @class = "control-label col-lg-4" }) @Html.EditorFor(model => model.device.AMCExpiredDate, new { htmlAttributes = new { @class = "form-control", placeholder = "AMCExpireDate(MM/dd/yyyy)", required = "required", title = "Enter AMC Expire Date" } })

在这里我需要设置必填字段“AMCExpiredDate”,如果“HasAMC”的值选择“true”然后对必填字段应用validation,如果它是假,则从“AMCExpiredDate”中删除validation。

这在MVC中是否可行? 请帮我。 提前致谢。

将您的视图更改为此类似的内容

  
@Html.LabelFor(model => model.device.HasAMC, htmlAttributes: new { @class = "control-label col-lg-4" }) @Html.EditorFor(model => model.device.HasAMC, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model => model.device.AMCExpiredDate, htmlAttributes: new { @class = "control-label col-lg-4" }) @Html.EditorFor(model => model.device.AMCExpiredDate, new { htmlAttributes = new { @class = "form-control", placeholder = "AMCExpireDate(MM/dd/yyyy)", required = "required", title = "Enter AMC Expire Date" } }) // put validation-error @Html.ValidationMessageFor(model => model.device.AMCExpiredDate); @if (@ViewData.ModelState["AMCExpiredDate"] != null && @ViewData.ModelState["AMCExpiredDate"].Errors.Count > 0) {
@ViewData.ModelState["AMCExpiredDate"].Errors[0].ErrorMessage.Trim() }
// create hidden field of your model variables @Html.HiddenFor(modelItem => model.device.HasAMC) @Html.HiddenFor(modelItem => model.device.HasAMC)

在服务器端

 public ActionResult SaveMarks(mymodelClass model) if (model.device.HasAMC) { // validat you AMCExpiredDate expir date e.georgian if(model.device.AMCExpiredDate == null) { ModelState.AddModelError("AMCExpiredDate", "Please Proive you AMCExpiredDate"); } }