I created a simple model with FluentValidation, but it does not work.
- My database is updated with an empty name and passed to
TryUpdateModel() - I do not get client side validation errors when submitting my form
I tried adding FluentValidationModelValidatorProvider.Configure(); in Application_Start() , but it shows that it cannot find the FluentValidationModelValidatorProvider , although I added the use of the class. I also tried adding [Validator(typeof(Category))] on top of the model class, but did nothing. This is the resource I was looking for.
Model
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."); } }
controller
[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); }
source share