这是我的观看代码:
<div class="form-group-1">
@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" } })
</div>
<div class="form-group-1" id="HasDate">
@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" } })
</div>
<button style="margin-left:33%;" class="btn btn-sm btn-primary col-lg-2 " type="button" name="action" onclick="javascript:Save(@ViewBag.DealerId);" value="SaveDeviceInfo"><strong>Save</strong></button>
在此我需要设置必填字段“AMCExpiredDate”,如果“HasAMC”的值选择为“true”,则对必填字段应用验证,如果为false,则从“AMCExpiredDate”中删除验证。
这可能在MVC中吗? 请帮我。在此先感谢。
答案 0 :(得分:2)
将您的观点更改为此类
<div class="form-group-1">
@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" } })
</div>
<div class="form-group-1" id="HasDate">
@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)
{
<br/>
<span class="field-validation-error col-md-10" style="margin-left: -14px;">
@ViewData.ModelState["AMCExpiredDate"].Errors[0].ErrorMessage.Trim()
</span>
}
</div>
<button style="margin-left:33%;" class="btn btn-sm btn-primary col-lg-2 " type="button" name="action" onclick="javascript:Save(@ViewBag.DealerId);" value="SaveDeviceInfo"><strong>Save</strong></button>
// 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");
}
}