使用流畅验证的基于属性的验证似乎不适用于asp.net-mvc

时间:2011-03-21 17:30:29

标签: asp.net-mvc fluentvalidation fluentvalidation-2.0

我在本教程中遵循了所有这些步骤:

创建了验证器类

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上添加一个属性以特定此验证员

[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 个答案:

答案 0 :(得分:2)

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

查看我在Fluent验证论坛上发布的这两个问题: http://fluentvalidation.codeplex.com/discussions/250798 http://fluentvalidation.codeplex.com/discussions/253389

相关问题