I'm learning ASP.NET MVC from the book Pro ASP.NET MVC 4 (which I love so far, by the way).
I'm still in the beginning chapters and it's showing me the System.ComponentModel.DataAnnotations namespace attributes, how to sprinkle my model class with these annotations, and then how to use them to check if the model is valid (ModelState.IsValid in the Controller).
For example:
public class GuestResponse
{
[Required(ErrorMessage = "Please enter your name"]
public string Name { get; set; }
}
...
public ViewResult RsvpForm(GuestResponse guestResponse)
{
if(ModelState.IsValid)
{
return View("Thanks", guestResponse);
}
}
There are a couple things about this that make me uneasy.
- Why do I want a bunch of attributes littered throughout my domain model? I like my domain model pure and free from any stuff that is implementation specific, and any real world model would be too complex to just use declarative validation like this.
- Aren't the
ErrorMessageparameters of the validation attributes somewhatViewrelated? Doesn't something like that belong in theUIlayer? For example...what if due to space constraints I want the mobile version to instead of saying "Please enter your name" say "Name required"? But here it is in my model! - Why do I want to use
ModelState.IsValidto determine the status of the model? Shouldn't the model tell me? I understand thatModelStateis making use of theDataAnnotationsattributes that are in my model, but this seems like it would only work for very simple models. A more complex model might not even have a valid/invalid state, it might just have various stages and states. I'm sort of rambling here, but I don't like the idea of declaratively saying what makes my model valid or invalid.
Any advice, reassurance, or validation of these thoughts would be appreciated.