【发布时间】:2019-03-18 15:17:41
【问题描述】:
我正在尝试使用自定义验证属性来确保复选框最终被选中。但是,在验证触发之前,验证错误会作为复选框标签的一部分显示(未设置样式)。
详细说明:
我有以下属性和属性:
[Display(Name = "TermsAndConditions", ResourceType = typeof(Res.Labels))]
[MustBeTrue(ErrorMessageResourceName = "TermsAndConditionsValidationMessage", ErrorMessageResourceType = typeof(Res.Labels))]
public bool TermsAndConditions { get; set; } = true;
(无论出于何种原因。默认为 true 是故意的。它在视图上换回 false):
@model MyModel
@{
MyModel.TermsAndConditions = false;
}
自定义属性如下所示:
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value is bool && (bool)value;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(Labels.TermsAndConditions),
ValidationType = "mustbetrue"
};
}
}
视图中的 HTML 如下所示:
<div class="checkbox">
@Html.CheckBoxFor(m => m.TermsAndConditions, true)
<div class="state">
<label for="terms">
@Html.Raw(Label.TermsAndConditions)
@Html.ValidationMessageFor(m => m.TermsAndConditions, Label.TermsAndConditionsValidationMessage)
</label>
</div>
</div>
使用 HTML.Raw 是因为我需要标签来呈现锚元素,我找不到其他方法。
页面加载时生成的 HTML 如下:
<div class="checkbox">
<input data-msg-mustbetrue="You must accept the terms and conditions" data-msg-required="The I aceept the <a href="#">terms and conditions</a>. field is required." data-rule-mustbetrue="true" data-rule-required="true" id="TermsAndConditions" name="TermsAndConditions" type="checkbox" value="true">
<input name="TermsAndConditions" type="hidden" value="false">
<div class="state">
<label for="terms">
I aceept the <a href="#">terms and conditions</a>.
<span class="field-validation-valid" data-valmsg-for="TermsAndConditions" data-valmsg-replace="false">You must accept the terms and conditions</span>
</label>
</div>
</div>
触发验证后,一切正常:
<div class="checkbox">
<input data-msg-mustbetrue="You must accept the terms and conditions" data-msg-required="The I aceept the <a href="#">terms and conditions</a>. field is required." data-rule-mustbetrue="true" data-rule-required="true" id="TermsAndConditions" name="TermsAndConditions" type="checkbox" value="true" class="input-validation-error">
<input name="TermsAndConditions" type="hidden" value="false">
<div class="state">
<label for="terms">
I aceept the <a href="#">terms and conditions</a>.
<span class="field-validation-error" data-valmsg-for="TermsAndConditions" data-valmsg-replace="false">You must accept the terms and conditions</span>
</label>
</div>
</div>
一段时间以来,我一直在用这些东西把头撞在墙上,有人能指出我正确的方向吗?请和谢谢。
【问题讨论】:
-
可以在属性上设置:[DefaultValue(false)]设置默认值,避免在视图中设置为false。
-
或从条款和条件中删除 =true { get;放; } = 真
-
感谢@NomiAli,ViewModel 是在用户实际看到视图之前使用的,所以 Page.IsValid 返回 false,除非它设置为 true,因此它是按照我的方式完成的。跨度>
标签: c# asp.net-mvc razor attributes html-helper