With an MVC application should my business rule validation be replicated in the view model and/or controller?
My MVC application has a well defined domain Model with each Model performing its own business rule checks.
My question is should the business rules be replicated in the view model or controller too or should I just allow the model to generate the validation errors?
Lets assume that the validation we are talking about can't be done client-side and is more complicated than simple field validation that can be done by adding validation attributes to the view model properties.
The problem with allowing the model to handle all of the validation is that the error messages it generates might not be suitable for the particular view that its coupled to, field names might not be correct for example. Also开发者_如何学JAVA I need to add the error to the ModelState using the view model property name not the property name from the domain model.
The problem with adding the same business rule validation to the viewmodel/controller is the obvious duplication maintenance issue and it means the validation in my domain model really should never produce any errors which kind of makes it a bit pointless.
How do people usually handle this?
The solution I typically used to use in this scenario is to have the validation in the Model (or in my case typically a validation library) but add the error in the controller which allows you to catch the standard validation error like this:
public ActionResult Submit(String email)
{
string errorMessage = "";
if(Validation.IsValidEmail(email, out errorMessage))
{
ViewData.AddModelError("EmailAddress", "My Custom Error Message");
//or
ViewData.AddModelError("EmailAddress", errorMessage);
}
}
This may not be exactly what you are looking for but it might help you come up with a way of maximising re-usable code whilst still being able to customise it.
I used to do it like this - but I bit the bullet and my most recent applications use standard error messages everywhere - my motivation for this is that users are increasingly comfortable with short-simple validation message and field names are not required in the message if the message is displayed inline with the form field rather than as a summary. This also allows me to put all my rules/messages in data annotations and I find that it works a treat.
精彩评论