Asp.NET MVC - DataAnnotations and ModelState.IsValid too invasive into the domain model?

Viewed 3070

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.

  1. 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.
  2. Aren't the ErrorMessage parameters of the validation attributes somewhat View related? Doesn't something like that belong in the UI layer? 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!
  3. Why do I want to use ModelState.IsValid to determine the status of the model? Shouldn't the model tell me? I understand that ModelState is making use of the DataAnnotations attributes 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.

3 Answers
Related