我正在使用数据注释进行客户端验证。我有两个使用[Required]
和[RequiredIfTrue]
的方案。问题是我的条件验证无效。
工作:
型号:
[DisplayName(@"Custom Email Confirmation Address")]
[EmailAddress(ErrorMessage = @"Invalid Email Address")]
public string CustomEmailConfirmationAddress { get; set; }
查看:
<div>
<%=Html.RequiredLabelFor(m => m.CustomEmailConfirmationAddress) %>
<%=Html.TextBoxFor(m => m.CustomEmailConfirmationAddress, new { maxlength = 100 })%>
<%=Html.ValidationMessageFor(m => m.CustomEmailConfirmationAddress)%>
</div>
不工作:
场景=如果选中ShowConceptOptInMessage
,则需要生成ConceptEmailOptInMessage
和PrivacyPolicy
字段。
型号:
[DisplayName("Show Concept Opt-In Message")]
public bool ShowConceptOptInMessage { get; set; }
[RequiredIfTrue("ShowConceptOptInMessage", ErrorMessage = "Concept Email Opt-In Message is required")]
[DisplayName("Concept Email Opt-In Message")]
public string ConceptEmailOptInMessage { get; set; }
[RequiredIfTrue("ShowConceptOptInMessage", ErrorMessage = "Concept Privacy Policy is required")]
[DisplayName("Concept Privacy Policy")]
public string PrivacyPolicy { get; set; }
查看:
<div>
<%=Html.LabelFor(m => m.ShowConceptOptInMessage) %>
<%=Html.CheckBoxFor(m => m.ShowConceptOptInMessage)%>
<%=Html.ValidationMessageFor(m => m.ShowConceptOptInMessage)%>
</div>
<div>
<%=Html.LabelFor(m => m.ConceptEmailOptInMessage) %>
<%=Html.TextAreaFor(m => m.ConceptEmailOptInMessage, new { maxlength = 1000 })%>
<%= Html.ValidationMessageFor(m => m.ConceptEmailOptInMessage)%>
</div>
<div>
<%=Html.LabelFor(m => m.PrivacyPolicy) %>
<%=Html.TextAreaFor(m => m.PrivacyPolicy)%>
<%= Html.ValidationMessageFor(m => m.PrivacyPolicy)%>
</div>
两种情况的控制器方法:
控制器:
[HttpPost]
public ActionResult Edit(ConceptConfigurationModel model)
{
try
{
if (this.ModelState.IsValid)
{
// model
this.ConceptManager.SaveConcept(model);
model.Submitted = true;
}
}
catch (BusinessLogicException ex)
{
this.ModelState.AddModelError("ConceptName", ex.Message);
}
ModelState.Clear();
this.ConceptManager.FillConceptModel(model);
return View(model);
}
答案 0 :(得分:2)
使用ASP.NET MVC 4,RequiredIf不起作用,我使用jquery unobtrusive实现了相同,添加下面的javascript方法
function AddValidation()
{
var showConceptOptInMessage = $("#ShowConceptOptInMessage").val();
if(showConceptOptInMessage)
{
$("#ConceptEmailOptInMessage").attr('data-val-required', 'Concept Email Opt-In Message is required');
$("#PrivacyPolicy ").attr('data-val-required', 'Concept Privacy Policy is required');
}
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
}