If I am using the MVVM pattern to populate my views, i.e. I am using a View Model in addition to the model classes. The model classes do not talk to the view; the view model populates the view.
In such a scenario, if I need to use data annotations for validation, etc. I need to annotate my view model classes and not my model classes, right?
For e.g. should the [Required] attribute be annotated on:
namespace MyApp.ViewModels
{
public class Category
{
[Required]
[StringLength(50)]
public string CategoryName { get; set; }
[StringLength(255)]
[AllowHtml]
public string Description { get; set; }
}
}
Or should it be this way:
namespace MyApp.Models
{
public partial class Category
{
[Required]
public virtual string CategoryName
{
get;
set;
}
}
}
Correct, your viewmodel should not use Models(entity) but can contain model properties, example:
this is a better use of viewmodel:
and yes, your annotations should be on the viewmodel.
You can set annotations to complex type in the viewmodel too, but please note that complex type should not be a entity/domain class, but a data model class specific only to viewmodel, example: