I have made a simple model that has FluentValidation in it but it does not seem to work.
TryUpdateModel()
I have tried to add FluentValidationModelValidatorProvider.Configure();
in Application_Start()
but it shows that it cannot find FluentValidationModelValidatorProvider
even though I added using class. I also tried to add [Validator(typeof(Category))]
on top of my model class but didn't do anything. This us the resource I've been looking for information.
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);
}
It sounds like you're missing the FluentValidation.Mvc
reference. Try installing the FluentValidation.MVC4 NuGet package.
Then follow the MVC instructions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With