Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Validation in ViewModel or Model?

Tags:

c#

asp.net-mvc

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?

like image 829
Pow4Pow5 Avatar asked Mar 10 '23 12:03

Pow4Pow5


1 Answers

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.

like image 120
Brian Ogden Avatar answered Mar 20 '23 14:03

Brian Ogden