ASP. net mvc series: add model validation rules, asp. netmvc
First, reference System in the model class. componentModel. dataAnnotations namespace; System. componentModel. the DataAnnotations namespace provides definitions for ASP. net mvc and ASP. NET data control class features (that is, built-in verification properties, you can use any declared class or attribute)
When no attribute is added, empty data can be added, such as the Title field below.
Now we add verification features to all attributes of the Movie class, and then run
Public class Movie {public int ID {get; set;} [Required] // the submitted data is not empty public string Title {get; set;} public DateTime ReleaseDate {get; set;} public string Genre {get; set;} [Range (1,100)] // the submitted data is 1 to 00 public decimal Price {get; set ;} [StringLength (5)] // The length of the submitted string is 5 public string Rating {get; set ;}}
However, when the http: // localhost: 60534/Movies homepage is opened, an exception is reported -- "System. invalidOperationException "type exception in EntityFramework. dll, but not in user code
Because we have changed the model and need to correspond to the database, we need to open the console again and enter the following commands (each time we add verification features or modify them, we need to execute them)
add-migration AddDataAnnotationsMig
update-database
This time you can smoothly open the http: // localhost: 60534/Movies/index page. Now we open the create page of Movie and click Submit, you will find that you cannot submit the data that requires us to enter the necessary data. Even if the browser activity script is disabled, the background code still needs to pass verification before submitting the data.
System. ComponentModel. DataAnnotations has many built-in features. We can also control the output style of model data through the DisplayFormat feature.
http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model