1. General situation
For those who have used the MVC framework, they will be familiar with MVC data verification. For example, I have a Model As follows:
1 public class UserInfo2 {3 [Required(ErrorMessage = "UserName不可为空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 end:
1 @using (Html.BeginForm()) 2 { 3 @Html.AntiForgeryToken() 4542 }UserInfo
6
7 @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 89 @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })101511 @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })12 @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })131416 @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })172218 @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })19 @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })202123 @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })242925 @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })26 @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })272830 @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })313632 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })33 @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })3435374138 3940
Effect:
2. Common situations
In actual development, we mostly use EF or other methods to make every Tables or views correspond to a class model in the code. For the model generated through the database, we should not modify it. To take a step back, even if we add some data verification features to some attributes in this class, then the database will change. Later, if I regenerate these Models, the verification features we added before will be gone. So, how do we solve this problem? Suppose: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 }
1 public partial class UserInfo2 {3 [Required(ErrorMessage = "UserName不可为空1111")]4 public string UserName { get; set; }5 }
1 [MetadataType(typeof(MeteUserInfo))]2 public partial class UserInfo3 {4 private class MeteUserInfo5 {6 [Required(ErrorMessage = "UserName不可为空1111")]7 public string UserName { get; set; }8 }9 }
The above is the detailed content of Summary of data validation examples in MVC. For more information, please follow other related articles on the PHP Chinese website!