Detailed description of MVC data verification and mvc Verification
I. general situation
For those who have used the MVC framework, it is no stranger to MVC data verification. For example, I have a Model as follows:
Public class UserInfo {[Required (ErrorMessage = "UserName cannot be blank 1111")] public string UserName {get; set;} public string Sex {get; set ;} public string Mobile {get; set;} public string Address {get; set ;}}
Front end:
@using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal">
Effect:
Yes, MVC can verify data by adding certain features to some attributes. This may not be a stranger to everyone.
If it's just like this, it's okay.
Ii. common situations
In actual development, we usually use EF or other methods to make every table or view in the database a class model corresponding to the code, we should not modify the model generated through the database. Let's take a look back. Even if we add some data verification features to some attributes in this class, after the database changes, if I re-generate these models, we will not have the verification feature we have added. How can we solve this problem?
Suppose:
public class UserInfo { public string UserName { get; set; } public string Sex { get; set; } public string Mobile { get; set; } public string Address { get; set; } }
UserInfo is a model generated by the database. We cannot modify the model generated by the database. But that is, we need to perform data verification on some attributes in this model. For example, we need to perform non-empty verification on the UserName attribute. What should we do?
We usually think of partial classification. Yes, we can solve the above problems through partial classification.
First, we add the keyword partial to the class in the model, and then write a partial classification for the model.
Public partial class UserInfo {[Required (ErrorMessage = "UserName cannot be blank 1111")] public string UserName {get; set ;}}
However, this will prompt us an error, that is, duplicate attributes exist in the class. Yes, attributes cannot be renamed in the partial classification. So what should we do? The MVC framework has already provided us a solution.
We can write as follows:
[MetadataType (typeof (MeteUserInfo)] public partial class UserInfo {private class MeteUserInfo {[Required (ErrorMessage = "UserName cannot be blank 1111")] public string UserName {get; set ;}}}
In this way, the above problems will be solved.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.