ASP. NET MVC's data validation mechanism is much more efficient than the ASP. NET WebForm. The following two examples are documented below for easy reference at a later date.
Method One: In the controller through the Addmodelerror method to return the wrong authentication information, take a look at the code example:
Controller, pay attention to see, he add when the submission is HttpPost, and the transfer of the parameter is a model come in.
PublicActionResult Add () {returnView (); } [HttpPost] Publicactionresult Add (Package.Model.Message Message) {if(Message.gname = =NULL) {Modelstate.addmodelerror ("Gname","the name cannot be empty"); } if(Message.gcontent = =NULL) {Modelstate.addmodelerror ("gcontent","content cannot be empty"); } if(modelstate.isvalid) {messagedal Msgdao=NewMessagedal (); Msgdao.add (message); returnView (); } returnView (); } }
Inside the View
@model package.model.message@{Layout = null;}<!DOCTYPE HTML><HTML><Head> <Metaname= "Viewport"content= "Width=device-width" /> <title>Add</title></Head><Body> <Div>@using (Html.BeginForm ()) {@Html. ValidationSummary (True); <fieldset> <legend>I want to leave a message</legend> <Div>message Name: @Html. textboxfor (A = a.gname) @Html. Validationmessagefor (A = A.GN AME)</Div> <Div>message content: @Html. textboxfor (A = a.gcontent) @Html. Validationmessagefor (A + a). Gcontent)</Div> <inputtype= "Submit"ID= "Btnadd"value= "Submit Message" /> </fieldset> } </Div></Body></HTML>
Method Two: Add validation directly to the model layer
How to give data validation to model? Here we need to quote a DLL:System.ComponentModel.DataAnnotations
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.ComponentModel.DataAnnotations;usingSystem.Text;namespacepackage.model{/// <summary> ///Message: Entity Class (Property description automatically extracts the description of a database field)/// </summary>[Serializable] Public Partial classMessage { PublicMessage () {}#regionModelPrivate int_id; Private string_gname; Private string_gcontent; Public intId {Set{_id =value;} Get{return_id;} } [DisplayName ("name")] [Required (Allowemptystrings=false, errormessage ="txxx cannot be empty")] Public stringGname {Set{_gname =value;} Get{return_gname;} } [Required (Allowemptystrings=false, errormessage ="DDASDASD cannot be empty")] Public stringgcontent {Set{_gcontent =value;} Get{return_gcontent;} } #endregionModel }}
More rich examples that are validated in model:
namespacemvcapplication4.models{ Public classUserInfo {//ID Number[Scaffoldcolumn (false)] [Required (Allowemptystrings=false, errormessage ="User ID cannot be empty")] [Display (Name="Record number", Order =20000)] Public intID {Get;Set; } [Display (Order=15000)] [Required (Allowemptystrings=false, errormessage ="user name cannot be empty")] [Stringlength ( -, Minimumlength =6, errormessage ="user name cannot be greater than {2} and is less than {1}")] [Remote ("User","Validate", HttpMethod ="Post", errormessage ="user name already exists")] Public stringUserName {Get;Set; } [Display (Name="Password")] [DataType (Datatype.password)] [Required (Allowemptystrings=false, errormessage ="The password cannot be empty")] [Stringlength ( -, Minimumlength = -, errormessage ="the password must be between {2} and {1}")] Public stringUserPassword {Get;Set; } [Required (Allowemptystrings=false, errormessage ="e-mail must be filled")] [RegularExpression (@"[A-za-z0-9._%+-][email protected][a-za-z0-9]+\. [A-za-z] {2,4}", errormessage ="the {0} is not in the correct format")] Public stringEmail {Get;Set; } [Compare ("Email", errormessage ="mailbox to be the same")] Public stringTemail {Get;Set; }//Compare if the case is the same, the validation will not be triggered[Display (Name="ID Number")] [RegularExpression (@"\d{17}[\d|x]|\d{15}", errormessage ="ID number format error")] Public stringIdentityno {Get;Set; } [Required (Allowemptystrings=false, errormessage ="age must be filled")] [Range (Ten, -, errormessage ="age cannot be greater than {2} cannot be less than {1}")] Public intAge {Get;Set; } [ReadOnly (true)] [DisplayFormat (Applyformatineditmode=true, dataformatstring ="{0:C}")] [Required (ErrorMessage="The amount cannot be empty")] [Range (typeof(decimal),"20.0","30.0", errormessage ="amount between {1} and {2}")] Public decimalMoney {Get;Set; } }}
Reference article: http://www.cnblogs.com/jiagoushi/archive/2013/01/25/2876725.html
ASP. NET mvc-data validation mechanism