2011-03-21 159 views
1

我遵循了所有在本教程下列步骤来:基于属性的验证似乎不使用asp.net-MVC

创建一个验证器类

public class ProjectValidator : AbstractValidator<ProjectViewModel> 
{ 
    public ProjectValidator() 
    { 
     //RuleFor(h => h.Milestone).NotEmpty().WithName("Milestone"); 
     RuleFor(h => h.Applications).NotNull().WithName("Application"); 
     RuleFor(h => h.InitiativeName).NotNull().WithName("Business Aligned Priority"); 
     RuleFor(h => h.BusinessDriverId).NotNull().WithName("Business Driver"); 
     RuleFor(h => h.FundingTypeId).NotNull().WithName("Funding Type"); 
     RuleFor(h => h.Description).NotEmpty().WithName("Description"); 
     RuleFor(h => h.Name).NotEmpty().WithName("Project Name"); 
     RuleFor(h => h.Sponsors).NotNull().WithName("Sponsors"); 
    } 
} 

把一个属性上我的DTO具体这个validtor

[Validator(typeof(ProjectValidator))] 
public class ProjectViewModel 
{ 
} 

但后一种形式后,当我去检查的ModelState错误列表中,我看到的错误是从asp.net MVC的默认验证到来。

public ActionResult UpdateMe(ProjectViewModel entity) 
    { 
     Project existingProject = this.Repository.Fetch<Project>(entity.Id); 

     UpdateProperties(entity, existingProject); 
     var allErrors = ModelState.Values.SelectMany(v => v.Errors); 
     if (allErrors.Count() > 0) 
     { 

对于为什么它没有采取流利的任何建议。验证器 ??我已经添加下面的图片是我在GUI

enter image description here

看看我直接在代码中调用验证它工作得很好:

ProjectValidator validator = new ProjectValidator(); 
ValidationResult result = validator.Validate(entity); 

回答

1

我不知道是什么类型的HTML元素FundingTypeId是,但我假设它是一个下拉列表。如果没有选择,那么它会给你这个错误。这不幸是MVC与MVC集成的限制之一,这是由MVC的默认模型绑定器的糟糕设计引起的。该消息不是由FV生成的,而是由DefaultModelBinder生成的,在这种情况下,传入值不能转换为属性类型。

退房,我贴在了流利的验证论坛这2个问题: http://fluentvalidation.codeplex.com/discussions/250798 http://fluentvalidation.codeplex.com/discussions/253389