我希望在发布表单so i tried using fluent.validation
时覆盖默认的asp.net-mvc验证我创建了一个验证器类(ProjectValidator)
public class ProjectValidator : AbstractValidator<Project>
{
public ProjectValidator()
{
RuleFor(h => h.Application).NotNull().WithName("Application");
RuleFor(h => h.FundingType).NotNull().WithName("Funding Type");
RuleFor(h => h.Description).NotEmpty().WithName("Description");
RuleFor(h => h.Name).NotEmpty().WithName("Project Name");
}
}
我在我的数据传输对象类中放置了一个属性
[Validator(typeof(ProjectValidator))]
public class ProjectViewModel
{
...
}
我把它放在application_start();
中 DataAnnotationsModelValidatorProvider
.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
但是当我发布使用此对象的表单时,我收到以下错误:
找不到方法:'System.Collections.Generic.IEnumerable`1 FluentValidation.IValidatorDescriptor.GetValidatorsForMember(System.String)'。
有什么建议吗?
答案 0 :(得分:2)
这可能是与您正在使用的程序集版本相关的问题。以下是使用最新版本的FluentValidation.NET和ASP.NET MVC 3的步骤:
FluentValidation.MVC3
NuGet包。添加视图模型及其相应的验证器(请注意,在您的情况下,您具有类型项目 - AbstractValidator<Project>
的验证器,而您的视图模型称为{{1}这是不一致的。验证器必须与视图模型相关联:
ProjectViewModel
在public class ProjectValidator : AbstractValidator<ProjectViewModel>
{
public ProjectValidator()
{
RuleFor(h => h.Application).NotNull().WithName("Application");
RuleFor(h => h.FundingType).NotNull().WithName("Funding Type");
RuleFor(h => h.Description).NotEmpty().WithName("Description");
RuleFor(h => h.Name).NotEmpty().WithName("Project Name");
}
}
[Validator(typeof(ProjectValidator))]
public class ProjectViewModel
{
public string Application { get; set; }
public string FundingType { get; set; }
public string Description { get; set; }
public string Name { get; set; }
}
注册验证器:
Application_Start
定义控制器:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
}
观点:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new ProjectViewModel());
}
[HttpPost]
public ActionResult Index(ProjectViewModel model)
{
return View(model);
}
}