C# MVC&x2019;s DefaultModelBinder不验证该对象
我正在使用FluentValidation MVC5验证对象。我注意到了这一点。当我发布表单时,为什么MVC DefaultModelBinder不验证该对象?FluentValidationModelValidatorProvider已在global.asax中配置C# MVC&x2019;s DefaultModelBinder不验证该对象,c#,asp.net-mvc,asp.net-mvc-5,fluentvalidation,C#,Asp.net Mvc,Asp.net Mvc 5,Fluentvalidation,我正在使用FluentValidation MVC5验证对象。我注意到了这一点。当我发布表单时,为什么MVC DefaultModelBinder不验证该对象?FluentValidationModelValidatorProvider已在global.asax中配置 protected void Application_Start() { FluentValidationModelValidatorProvider.Configure(); } Global.asax protect
protected void Application_Start()
{
FluentValidationModelValidatorProvider.Configure();
}
Global.asax
protected void Application_Start()
{
FluentValidationModelValidatorProvider.Configure();
}
ClientValidationEnabled和UnobtrusiveJavaScriptEnabled在web.config中设置为true。
我还下载了最新的jquery.validation包,添加到BundleConfig,并在其视图(Create.cshtml)中添加了
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
CurrencyViewModel.cs
[Validator(typeof(CurrencyViewModelValidator))]
public class CurrencyViewModel
{
public int CurrencyID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class CurrencyViewModelValidator : AbstractValidator<CurrencyViewModel>
{
public CurrencyViewModelValidator()
{
RuleFor(x => x.Code).Length(3);
RuleFor(x => x.Name).Length(3, 50);
}
}
货币中的值为null,但ModelState.IsValid为true,这很奇怪
这是完全正常的行为。验证程序检查字符串长度,而不是属性是否为空:
确保特定字符串属性的长度在指定范围内
如果不希望允许空值,则应使用验证程序:
RuleFor(x => x.Code).NotNull().Length(3);
RuleFor(x => x.Name).NotNull().Length(3, 50);
在VS中,将断点放在if(ModelState.IsValid)行中,然后检查模型中的值以查看导致错误的原因。@NareshRavlani货币中的值为空,但ModelState.IsValid为真,奇怪。它不应该到达ModelState.IsValid如果客户端验证正在工作解决,谢谢@Zabavsky,我不知道null值我可以问你另一个问题吗?在使用FluentValidation之前,我正在CurrencyMetaData类中使用DataAnnotation进行验证。因此,我可以删除CurrencyMetaData类,因为它不再使用,或者除了验证之外还有其他功能吗?您的元数据类可以包含验证之外的其他注释属性,如
DisplayAttribute
,DataTypeAttribute
等。,但是对于验证,您必须使用DataAnnotation
或FluentValidation
。