gpt4 book ai didi

c# - 尝试使用自定义验证属性时出现 System.InvalidOperationException

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:27 26 4
gpt4 key购买 nike

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

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

[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)

我完全不知所措,有人能指出我正确的方向吗?谢谢。

最佳答案

事实证明,所描述的不是问题。我不太确定此时的异常是什么,但它在新的验证代码出现之前就已经存在了。验证代码实际上在正常工作,但是由于网站的构建方式,它会在我们看到 View 之前尝试验证模型,因此 View 永远不会加载,因为复选框总是以 false 开始。

关于c# - 尝试使用自定义验证属性时出现 System.InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com