5

ASP.NETMVCプロジェクトで流暢な検証を使用しようとしています。ビューモデルを検証しようとしています。

これは私のビューモデルです、

[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モデルエラーをModalStateに追加できるように、Fluent検証を手動で構成する必要がありますか?

4

1 に答える 1

7

ドキュメントApplication_Startで説明されているように、データアノテーションモデルのメタデータプロバイダーを交換し、代わりに流暢な検証を使用するために、に次の行を追加したことを確認してください。

FluentValidationModelValidatorProvider.Configure();

また、あなたの行動における次のコメントは私を怖がらせます:

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

ビューモデルは、データベースの意味を認識してはなりません。したがって、ビューモデルにそのようなメソッドを含めることは非常に間違ったアプローチです。

于 2012-07-26T11:57:42.813 に答える