【发布时间】:2019-03-13 16:54:34
【问题描述】:
我正在尝试添加一个必须勾选才能进行的复选框,一个标准条款和条件声明。
环顾网络,所有问题的答案都是以下代码的一些变体:
[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)
我完全不知所措,有人能指出我正确的方向吗?谢谢。
【问题讨论】:
-
我们可以有完整的堆栈跟踪吗?
-
@canton7 - 这是它吐出的堆栈跟踪的唯一部分。不过现在不用介意,因为这个错误是完全不相关的,我在发现真正的问题之前就发现了它。我仍然不知道异常是什么,但它可以等待。至于 real 问题,复选框默认为 false,并且控制器和 ViewModel 连接的方式意味着它在加载之前进行验证。因为它一开始是假的,所以它永远不会加载。 IsValid 函数静默失败,但由于应用程序的当前性质,在该阶段没有返回错误,因此看不到它。
标签: c# .net asp.net-mvc validation asp.net-mvc-5