我正在尝试添加一个必须勾选进度的复选框,一个标准的条款和条件声明。
浏览网页,问题的所有答案都是以下代码的一些变体:
[Display(Name = "This Is A Test")]
[MustBeTrue(ErrorMessage = "come on!")]
//[MustBeTrue(ErrorMessageResourceType = typeof(Res.Text), ErrorMessageResourceName = "ValidationMessage")]
//[Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
public bool TermsAndConditions { get; set; }
自定义属性如下所示:
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(metadata.GetDisplayName()),
ValidationType = "mustbetrue"
};
}
}
然后类似于:
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
在我看来,我正在渲染复选框,如下所示:
@Html.CheckBoxFor(m => m.TermsAndConditions, false)
@Html.LabelFor(m => m.TermsAndConditions)
@Html.ValidationMessageFor(m => m.TermsAndConditions)
我已经尝试了很多变化,我总是遇到同样的例外:
System.InvalidOperationException
HResult=0x80131509
Message=The parameter conversion from type 'System.String' to type 'Nordics.Models.PolicyManagement.Affiliates.Affiliate' failed because no type converter can convert between these types.
Source=System.Web.Mvc
StackTrace:
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
我完全失去了,有人能指出我正确的方向吗?谢谢。
所以事实证明所描述的是一个非问题。我不太确定此时的异常是什么,但它在新的验证代码之前就已存在。验证代码实际上正常工作,但是由于构建网站的方式,它在我们可以看到视图之前尝试验证模型,因此视图永远不会加载,因为复选框始终以false开头。