asp.net-mvc - ASP.NET MVC ModelState始终通过Fluent验证有效

标签 asp.net-mvc viewmodel fluentvalidation

我正在尝试对ASP.NET MVC项目使用流利的验证。我正在尝试验证我的 View 模型。

这是我的 View 模型

[Validator(typeof(ProductCreateValidator))]
public class ProductCreate
{
    public string ProductCategory   { get; set; }
    public string ProductName       { get; set; }
    ....
}

这是我的验证器类(class),
public class ProductCreateValidator : AbstractValidator<ProductCreate> 
{
    public ProductCreateValidator()
    {
        RuleFor(product => product.ProductCategory).NotNull();
        RuleFor(product => product.ProductName).NotNull();
    }
}

在我的 Controller 中,我正在检查我的ModelState是否有效,
[HttpPost]
public ActionResult Create(ProductCreate model)
{
    /* This is a method in viewmodel that fills dropdownlists from db */
    model.FillDropDownLists();

    /* Here this is always valid */
    if (ModelState.IsValid)
    {
        SaveProduct(model);
        return RedirectToAction("Index");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

这就是我所拥有的。我的问题是当我的 View 模型完全为空时,ModelState.IsValid返回true。我是否需要手动配置Fluent验证,以便可以将模型错误添加到ModalState?

最佳答案

正如documentation解释的那样,请确保已在Application_Start中添加了以下行,以便交换数据注释模型元数据提供程序并改为使用流利的验证:

FluentValidationModelValidatorProvider.Configure();

另外,您的操作中的以下评论使我感到恐惧:
/* This is a method in viewmodel that fills dropdownlists from db */
model.FillDropDownLists();

View模型不应该知道数据库的含义。因此,在 View 模型中使用此类方法是非常错误的方法。

关于asp.net-mvc - ASP.NET MVC ModelState始终通过Fluent验证有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11668713/

相关文章:

asp.net-mvc - ASP.NET MVC View 模型最佳实践

c# - 避免为不同的表单重复字段

c# - 使用 FluentValidation.NET 进行条件规则评估

c# - 使用带有命名参数列表的 FluentValidation 的 WithMessage 方法

javascript - 停止将 '' 编码为 Javascript 中的引号

asp.net-mvc - 找不到内容时,ASP.NET MVC 重定向到默认页面/路由

c# - 单个解决方案中的多个 MVC 项目

asp.net - VS2015 添加类库引用

android - 在 Android 中看不到 ViewModel 类

c# - FluentValidation NotEmpty 和 EmailAddress 示例