ASP.NET MVC ModelState始终对Fluent验证有效

emr*_*azi 4 asp.net-mvc viewmodel fluentvalidation

我试图使用ASP.NET MVC项目的流畅验证.我正在尝试验证我的视图模型.

这是我的viewmodel,

[Validator(typeof(ProductCreateValidator))]
public class ProductCreate
{
    public string ProductCategory   { get; set; }
    public string ProductName       { get; set; }
    ....
}
Run Code Online (Sandbox Code Playgroud)

这是我的验证员班,

public class ProductCreateValidator : AbstractValidator<ProductCreate> 
{
    public ProductCreateValidator()
    {
        RuleFor(product => product.ProductCategory).NotNull();
        RuleFor(product => product.ProductName).NotNull();
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我正在检查我的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);
}
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 7

正如文档所解释的那样,请确保在您的服务器中添加了以下行Application_Start,以便交换数据注释模型元数据提供程序并使用流畅的验证:

FluentValidationModelValidatorProvider.Configure();
Run Code Online (Sandbox Code Playgroud)

你的行动中的以下评论也让我害怕:

/* This is a method in viewmodel that fills dropdownlists from db */
model.FillDropDownLists();
Run Code Online (Sandbox Code Playgroud)

View模型不应该知道数据库的含义.因此在视图模型中使用这样的方法是一种非常错误的方法.