Reputation: 2973
Following the article http://www.thekip.nl/2011/09/22/using-fluentvalidation-for-both-domain-validation-and-validation-in-mvc-projects/ for me it's not still clear where does the validation appear in application: on client side using ModelState.IsValid
? Or it could be used inside a controller?
EDIT
Ok. So for the given example
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dinner dinner) {
if(ModelState.IsValid) {
try {
dinner.HostedBy = "SomeUser";
dinnerRepository.Add(dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new {id = dinner.DinnerID });
} catch {
ModelState.AddRuleViolations(dinner.GetRuleViolations());
}
}
return View(dinner);
}
ModelState
corresponds to a Dinner
entity?
Thanks!
Upvotes: 1
Views: 634
Reputation: 39491
ModelState
always corresponds to model binding system. For any parameter that you action has got, and any validation errors when binding it, ModelState
is populated. ModelState
is of course on server side, and there's no way to check for it on client side. You should and can check it only in controller actually.
The pattern you posted as an example, is approved pattern for handling post requests in asp.net mvc. First check for ModelState.IsValid
gives you information whether client posted values cotain validation errors or not. If there're errors, you return same view populated for client to check values and correct them. If supplied values are valid, ModelState.IsValid
returns true
and you try to save it to repository. But that repository also may do its internal validation additionally and throw FluentValidation.ValidationException
. That's where you need the catch - to catch that validation exception and add it to ModelState
, so that mvc system could show validation errors to client
Modify that catch a little bit
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dinner dinner) {
if(ModelState.IsValid) {
try {
dinner.HostedBy = "SomeUser";
dinnerRepository.Add(dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new {id = dinner.DinnerID });
}
catch(ValidationException ex)
{
ValidationResult result = new ValidationResult(ex.Errors);
result.AddToModelState(ModelState, string.Empty);
}
}
return View(dinner);
}
Upvotes: 2