如何将FluentValidation集成到MVC4中

Sta*_*tan 5 c# asp.net asp.net-mvc fluentvalidation asp.net-mvc-4

我已经制作了一个包含FluentValidation的简单模型,但它似乎不起作用.

  • 我的数据库正在使用空名称和传递进行更新 TryUpdateModel()
  • 提交表单时,我没有收到客户端验证错误

我试图添加FluentValidationModelValidatorProvider.Configure();,Application_Start()但它表明,FluentValidationModelValidatorProvider即使我添加使用类,它也找不到.我也尝试添加[Validator(typeof(Category))]我的模型类但没有做任何事情.是我一直在寻找信息的资源.

模型

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    virtual public ICollection<Image> Images { get; set; }
}

public class CategoryValidator : AbstractValidator<Category>
{
    public CategoryValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Category name is required.");
    }
}
Run Code Online (Sandbox Code Playgroud)

调节器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Category c)
{
    var category = _db.Categories.Where(x => x.ID == c.ID).SingleOrDefault();
    if (category == null) return HttpNotFound();

    // Update model and return to category list
    if (TryUpdateModel(category)) // it passes with empty name and saves changes
    {
        _db.SaveChanges();
        return RedirectToAction("index", "category");
    }

    // Something is wrong, return view back
    return View(c);
}
Run Code Online (Sandbox Code Playgroud)

jru*_*ell 7

听起来你错过了FluentValidation.Mvc参考.尝试安装FluentValidation.MVC4 NuGet包.

然后按照MVC说明进行操作.