Summary of MVC4 data verification, features, automatic attributes, and mvc4 features
I recently learned a truth, and I will share it with you here: Education represents your past, your present abilities represent your present, and learning represents your future.
Ten years in Hexi, do not bully teenagers
There is no end to learning, keep improving
Recently I am working on self-taught MVC. I have encountered many problems. simply summarize them.
MVC4 data verification:
In this example, the program is used as an example to describe:
Public class MyModel {[Required (ErrorMessage = "Enter Recipient Name")] public string Uname {get; set;} [Required (ErrorMessage = "Enter recipient's mobile phone number")] [RegularExpression (@ "^ 1 [3458] [0-9] {9} $", ErrorMessage = "Incorrect Mobile Phone Number Format")] public string UMoblie {get; set ;} [Required (ErrorMessage = "select Province")] public string cmbProvince {get; set;} [Required (ErrorMessage = "select city/county")] public string cmbCity {get; set;} [Required (E RrorMessage = "select region")] public string cmbArea {get; set;} public int moren {get; set;} public string postnum {get; set ;} [Required (ErrorMessage = "please fill in the detailed address")] public string AddressInfo {get; set ;} [RegularExpression (@ "^ \ w + @ [a-zA-Z _] +? \. [A-zA-Z] {2, 3} $ ", ErrorMessage =" enter the correct Email address ")] public string Email {get; set;} [StringLength (18, errorMessage = "Incorrect ID card format! ")] Public string cardNum {get; set;} // 18-bit [StringLength (16, MinimumLength = 6, ErrorMessage =" the password length should be 6 ~ Between 18 bits)] [System. web. mvc. compare ("ConfimPassWords")] // The password entered twice must be the same as the previous public string NewPassWords {get; set ;}// the password length is 6 ~ 16-bit [DataType (DataType. Password)] [StringLength (16, MinimumLength = 6, ErrorMessage = "the Password length should be 6 ~ Between 18 bits)] [System. web. mvc. compare ("NewPassWords")] // The password entered twice must be the same as the previous public string ConfimPassWords {get; set ;}// the password length is 6 ~ 16-bit [DisplayFormat (ApplyFormatInEditMode = true, DataFormatString = "{0: c}")] public decimal money {get; set ;} // The DisplayFormat feature can be used to process various formatting options of attributes. When a property contains a null value, you can provide optional display text, disable HTML encoding for the Property containing tags, and specify a formatted string for the property value at runtime. [ReadOnly (true)] public decimal Price {get; set;} // indicates that read-only data cannot be modified. [Range (18, 60)] public int Age {get; set ;} // age range // order control the Order of field attributes [Required] [StringLength (160)] [Display (Name = "Last Name", order = 15001)] public string LastName {get; set;} [Required] [StringLength (160, MinimumLength = 3)] [Display (Name = "First Name", Order = 15000)] public string FirstName {get; set ;}
}
MVC features: Exclude, Include, Remote, HandleError, and HiddenInput
In form submission, if we do not want to submit certain attributes, we can use the Exclude feature to declare
In form submission, if we only submit some attributes, we can use the Include feature to declare
For example, we have the following Model
[Bind (Exclude = "Address")] // declare it on the top of the class. The public class Employee {public string Name {get; set;} is valid for all Action methods that reference this class ;} public string Email {get; set;} public string Address {get; set;} public string PhoneNo {get; set ;}}
When submitting a form, we do not submit the Address. In the Action method, we cannot obtain the Address value, as shown below:
Of course, if we do not aim at all methods, but just for one method, we can write the features on the method, as shown below:
In addition to the above: [Bind (Exclude = "Address")], we can also use Include to declare:
[Bind (Include = "Name, Email, PhoneNo")] // declare it on the top of the class, the Action method that references this class is valid for all public class Employee {public string Name {get; set;} public string Email {get; set;} public string Address {get; set ;} public string PhoneNo {get; set ;}}
Remote features
Suppose we have a registry ticket with a mailbox text box. after entering the mailbox, we want to check whether the entered mailbox already exists in the Database. If so, we will not submit the form, in this case, we can use RemoteAttribute. Through RemoteAttribute, we can perform some server-side verification before submitting a form.
We can use RemoteAttribute in the following example:
[Required]
[Remote ("CheckUserName", "Home")]
Public string UserName
{
Get;
Set;
}
The first parameter of RemoteAttribute is an Action name, the second parameter is the Controller name, and the third parameter is the prompt information displayed to the user if the mailbox already exists. After entering the email address, the CheckEmail method will be executed and check whether the email address exists.
public JsonResult CheckUserName(string UserName) { bool result = true; if (UserName == "admin") { result = false; } return Json(result,JsonRequestBehavior.AllowGet); }
HandleErrorThe description is as follows:
We already have many methods to handle exceptions in MVC, such as try catch, Filter, or elmah. However, MVC also provides HandleErrorAttribute to handle exceptions, as follows:
[HandleError()]public ActionResult CheckError() { int a = 10; int b = 0; int k = a / b; return View(); }
In the web. config file, we add the following two lines:
<customErrors mode ="On" defaultRedirect ="Error.cshtml"></customErrors>
Create a view Error. cshtml in the shared folder and run the program. If you run the preceding CheckError () method, the Error. cshtml you just created will be displayed.
You can also use handleerrorattri to display different view pages for different types of exceptions.
[HandleError(ExceptionType=typeof(DivideByZeroException),View="DivideByZeroErrorView")][HandleError(ExceptionType = typeof(NullReferenceException), View = "NullRefrenceErrorView")]public ActionResult CheckError() { int a = 10; int b = 0; int k = a / b; return View(); }
HiddenInput Attribute
If you want to hide some entity fields, you can use the HiddenInput feature.
public class Employee { [HiddenInput(DisplayValue=false)] public string Name { get; set; } [Remote("CheckEmail","Employee",ErrorMessage="Email is already exist")] public string Email { get; set; } public string Address { get; set; } public string PhoneNo { get; set; } }
In the above entities, I use the HiddenInput feature to describe the Name field. In this way, the Name field will not be displayed in the browser after the program runs. Therefore, HiddenInput adds some additional control to the object field to d.
C # automatic attributes:
In C #3.0 and later versions, when the attribute accessors do not need other logic, the automatically implemented attribute can make the attribute Declaration more concise.
The following example demonstrates the standard implementation and automatic implementation of attributes:
Class Program {class Person {// standard implementation attribute int _ age; public int Age {get {return _ age;} set {if (value <0 | value> 130) {Console. writeLine ("the specified age is incorrect! "); Return ;}_ age = value ;}// automatically implemented attribute public string Name {get; set ;}} static void Main (string [] args) {Person p = new Person (); p. age = 180; p. name = "Tom"; Console. writeLine ("{0} {1} years old. ", P. Name, p. Age); Console. ReadKey ();}}
The above automatic attribute controls the age range, which is very simple!
Another example is the automatic String Length truncation attribute I wrote.
/// <Summary> /// point list /// </summary> public partial class YX_weiUserJF {private string nickName; public string NickName {get {return nickName ;} set {nickName = value; if (CommonMethod. getStringLenth (nickName)> 16) {// when the length of the nickName is greater than 16 bits, extract the first two digits +... + The last two nicknames = nickName. substring (0, 2) + "... "+ nickName. substring (nickName. length-2, 2) ;}}} private int score; public int Score {get {return score ;}set {score = value ;}}}
Okay, that's all. It's easy!
Reference: Common MVC features
@ Chen Wolong's blog