I have a model
that contains basic information. However, my View
requires more information just for display so I think that a ViewModel
is needed here to display that extra information. However, should I add the Validation attributes
in the model so that when I perform Code-First migration
, it automatically creates the database
for me with the correct datatype
of each columns or should I add the Validation attributes
to the ViewModel since the form should validate
the filled information?
public class Module
{
[Key]
public int id { get; set; }
[Required]
[StringLength(100)]
[Column(TypeName = "varchar")]
[Display(Name="Module Name")]
public string ModuleName { get; set; }
}
public class ModuleViewModel
{
[Key]
public int id { get; set; }
[Required]
[StringLength(30)]
[Column(TypeName="varchar")]
[Display(Name="Module ID")]
public string ModuleID { get; set; }
[Required]
[StringLength(100)]
[Column(TypeName = "varchar")]
[Display(Name="Module Name")]
public string ModuleName { get; set; }
//To populate dropdownlist
public List<SelectListItem> ModuleLevelList { get; set; }
}
Do I really need a ViewModel
in this case?
Data Annotation attributes for user input validation go on the ViewModel. Data Annotations for Entity Framework Code First go on the Model.
They are conceptually two different things, validation of input and database generation using EF Code First.
For example, Required and StringLength for Entity Framework Code First creates a database column of type varchar(length) NOT NULL. Required and StringLength on the ViewModel are used in Validation of user input. Do not conflate the two, there is nothing wrong with using StringLength(length) twice. Put the length value in a static Constant if you want the length expressed one place only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With