System.InvalidOperationException 尝试使用自定义验证属性时

System.InvalidOperationException when attempting to use custom validation attribute

我正在尝试添加一个必须勾选才能进行的复选框,一个标准的条款和条件声明。

环顾网络,问题的所有答案都是以下代码的一些变体:

[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 开始。