I read this question and answers, about if Display Annotations on model properties violates the separation of concerns between view and model. And my interpretation of their answer was "No, not if you're using a ViewModel for Display Annotations". But additional separation of concerns questions arose as I began implementing.
I have two questions but both are kind of related to each other. In both, I am wondering if I am violating the separation of concerns:
- I'm using localized strings from my views/resources.resx in my Model for Display Attributes, does this violate the separation of concerns since it's a resource in my views folder intended for views?
- Do I need a ViewModel for my Model to keep separation of concerns? And if so, which Annotations need to go on my model's properties, and which need to go on the ViewModel properties?
I think I need to keep all the Display Annotations and Validation Annotations (like [required]
and [range(x,y)]
) that I have in my ViewModel. In my Model I think I need to keep just the Validation Annotations. But, If this is true, then I have two classes to maintain Validation Annotations if I decide to add another property!?
The reason I think that I need Validation Annotations on both classes is so that the Model class can tell EF to put the correct constraints into database when I change schema with DbMigrations. Also, so the ViewModel tells the browser to tell the user when he's putting an invalid value in.
The ViewModel
public class RestaurantReviewViewModel
{
public int Id { get; set; }
[Range(1, 10)]
[Required]
public int Rating { get; set; }
[Required]
[StringLength(1024)]
[Display(Name = Resources.Description)]
public string Body { get; set; }
[Display(Name = Resources.UserName)]
[DisplayFormat(NullDisplayText = "[Anonymous]")]
public string ReviewerName { get; set; }
public int RestaurantId { get; set; }
}
The attributes that I commented out in the next class are the attributes I think i need to remove for the Model.
The Model
public class RestaurantReviewModel
{
public int Id { get; set; }
[Range(1, 10)]
[Required]
public int Rating { get; set; }
[Required]
[StringLength(1024)]
//[Display(Name = Resources.Description)]
public string Body { get; set; }
//[Display(Name = Resources.UserName)]
//[DisplayFormat(NullDisplayText = "[Anonymous]")]
public string ReviewerName { get; set; }
public int RestaurantId { get; set; }
}