【问题标题】:ASP.NET MVC ModelState is always valid with Fluent ValidationASP.NET MVC ModelState 在 Fluent Validation 中始终有效
【发布时间】:2012-07-26 11:52:56
【问题描述】:

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

这是我的视图模型,

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

这是我的验证器类,

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

在我的控制器中,我正在检查我的 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);
}

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

【问题讨论】:

    标签: asp.net-mvc viewmodel fluentvalidation


    【解决方案1】:

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

    FluentValidationModelValidatorProvider.Configure();
    

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

    /* This is a method in viewmodel that fills dropdownlists from db */
    model.FillDropDownLists();
    

    视图模型不应该知道数据库的含义。所以在你的视图模型中使用这样的方法是一种非常错误的方法。

    【讨论】:

    • 非常喜欢。关于视图模型,我的视图中有几个下拉列表,我希望它们从 db 中填充。我可以采用什么方法来填补我当前的替代方案?
    • 我的简单方法是让控制器调用一个演示者。演示者有责任调用数据库来创建视图模型和填充列表。在更复杂的场景中,您还可以使用映射器从模型创建视图模型或从视图模型创建模型。在所有情况下,viewmodel 应该只知道自己,同时遵循仅引用原始类型的 POCO 模式。
    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 2011-02-09
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2015-07-09
    相关资源
    最近更新 更多