I. GENERAL SITUATION
For people who have used the MVC framework, the data validation of MVC is no stranger, for example, I have a model like this:
1 public class UserInfo2 {3 [Required (errormessage = "UserName not nullable 1111")]4 public string UserName { Get Set }5 public string Sex {get; set;} 6 Public string Mobile {get; set;} 7 public string Address {get; set;} 8 }
Front:
1 @using (Html.BeginForm ()) 2 {3 @Html. AntiForgeryToken () 4 <div class= "Form-horizontal" > 5
Effect:
Yes, MVC can validate data by adding certain attributes to some properties. This may not be a stranger to everyone.
If it's just that, then it's all right.
Second, the common situation
In the actual development, we mostly through the EF, or other means, so that every table or view in the database, in the code corresponding to a class model, for the model generated by the database, we should not modify, step back, even if we in this class to some of the properties of some data validation features, then, Once the database has changed, if I regenerate the model again, we will not have the validation features we added before, so how do we solve this problem?
If:
1 public class UserInfo2 { 3 public string UserName {get; set;} 4 public string Sex {get; set;} 5 public string Mobile {get; set;} 6 Public string Address {get; set;} 7 }
UserInfo is a model generated by the database, we should not modify the model generated by the database. But that is, we need to validate some of the properties in this model, such as the need for non-null validation of the Username property, so how do we do it?
We usually think of some classes, yes, we can solve these problems through some classes.
First, we add the class in the model to the keyword partial, and then we write a partial class of this model.
1 public partial class UserInfo2 {3 [Required (errormessage = "Username not nullable 1111")]4 public string UserName {get; set;} 5 }
However, this will prompt us with a mistake, that is, there are duplicate properties in the class, yes, in some classes, the attributes are not names. So, what do we do, the MVC framework has given us a solution.
We can write this:
1 [Metadatatype (typeof (Meteuserinfo))]2 public partial class UserInfo3 {4 private class MeteUserInfo5 {6 [Required (errormessage = "UserName not nullable 1111")]7 public string UserName {get; set;} 8 }9 }
In this way, we can solve the above problems.