asp.net MVC Form Verification Method Summary __.net

Source: Internet
Author: User

form validation of binding parameters: ( validated by binding to model by Validationattribute attribute )

1. Introduction of JS file:
A version of jquery

Jquery.validate.js

Jquery.validate.unobtrusive.js


2. In the site Web.config, the related properties must be set to true:

  <appSettings> ...

    <add key= "clientvalidationenabled" value= "true"/> "<add" key= "unobtrusivejavascriptenabled"

    true "/>

  </appSettings>


3. Add validation attributes or custom attributes to the view model used:


    public class Customer

    {

        [Required]

        [Validusernameattribue (errormessage = "User name can only be Darren")]

        [ Display (name = user name)] public

        string UserName {get; set;}

    }
   Custom validation attribute Validusernameattribue (inherited attribute class Validationattribute, overriding IsValid method)

   using System.ComponentModel.DataAnnotations;

 

   namespace. Extension

   {public

       class Validusernameattribue:validationattribute

       {public

           override bool IsValid ( Object value

           {

               //= Pass if 2 conditions are met, otherwise validation fails return

               (value!= null && value). ToString () = = "Darren");}}

   

4. Add validation to view
@using (Html.BeginForm ()) {@Html. ValidationSummary (True) <fieldset> <legend>album</legend&

        Gt <div class= "Editor-label" > @Html. Labelfor (model => model. Genreid, "genre") </div> <div class= "Editor-field" > @Html. DropDownList ("Genreid", String.Empty) @Html. Validationmessagefor (model => model. Genreid) </div> <div class= "Editor-label" > @Html. Labelfor (model => model. ArtistID, "Artist") </div> <div class= "Editor-field" > @Html. DropDownList ("ArtistID ", String.Empty) @Html. Validationmessagefor (model => model. ArtistID) </div> <div class= "Editor-label" > @Html. Labelfor (model => model. UserName) </div> <div class= "Editor-field" > @Html. Editorfor (model => model. UserName) @Html. ValidationmessaGefor (model => model. UserName) </div> <div class= "Editor-label" > @Html. Labelfor (model => model. Price) </div> <div class= "Editor-field" > @Html. Editorfor (model => model. Price) @Html. Validationmessagefor (model => model. Price) </div> <div class= "Editor-label" > @Html. Labelfor (model => model. Albumarturl) </div> <div class= "Editor-field" > @Html. Editorfor (Model => MODEL.A Lbumarturl) @Html. Validationmessagefor (model => model. Albumarturl) </div> <p> <input type= "Submit" value= "Create"/> < /p> </fieldset>}

5. On the server side:

if (modelstate.isvalid)
  {
   db. Albums.add (album);
   Db. SaveChanges ();
   Return redirecttoaction ("Index");
  }


Second, form verification of binding parameters ( by implementing the Ivalidatableobject interface to achieve model self-verification )

Steps 1, 2, 4, 5 ibid.,

Step 3: Implement the Ivalidatableobject interface and implement its Validate method in ViewModel:

In the implementation of the Validate method, we obtain the authenticated person object from the validation context and authenticate its property members individually. If the data member does not pass validation, we encapsulate the error message and the data member name (property name) with a Validationresult object, which ultimately returns a collection of element type Validationresult. asp.net MVC automatically invokes the method to validate the bound data object.

public class Person:ivalidatableobject {[DisplayName (' name ')] public string Name {get; set;}

    [DisplayName ("Gender")] public string Gender {get; set;} [DisplayName ("Age")] public int?

    Age {get; set;} Public ienumerable<validationresult> Validate (Validationcontext validationcontext) {Person person = VA
        Lidationcontext.objectinstance as person;
        if (null = = person) {yield break; } if (string. IsNullOrEmpty (person.
        Name) {yield return new Validationresult ("' Name is a required field", New string[]{"name"}); } if (string. IsNullOrEmpty (person.
        Gender)) {yield return new Validationresult ("' Gender ' is a required field", new string[] {"Gender"}); else if (!new string[]{"M", "F"}. Any (g=>string.compare. Gender,g, true) = = 0) {yield return new Validationresult ("Valid ' Gender ' must be ' M ', ' F '", new string[] {
        "Gender"});

  }      if (null = = person.
        Age) {yield return to new Validationresult ("' age ' is a required field", new string[] {"Age"}); else if (person. Age > 25 | | Person.
        Age < = {yield return to new Validationresult ("' age ' must be between 18-25 years old", new string[] {"Aged"}); }            
    }
}
Three. Form validation of binding parameters ( by implementing the IDataErrorInfo interface

Steps 1, 2, 4, 5 ibid.,

Step 3: Implement the IDataErrorInfo interface in ViewModel, and use its index parameters as properties.

The IDataErrorInfo interface is defined under the "System.ComponentModel" namespace, which provides a standard way of customizing error information. As shown in the following code fragment, IDataErrorInfo has two members, the read-only property error is used to get an error message based on itself, and the read-only index is used to return the error message for the specified data member.

public class Person:idataerrorinfo {[DisplayName (' name ')] public string Name {get; set;}

    [DisplayName ("Gender")] public string Gender {get; set;} [DisplayName ("Age")] public int?

    Age {get; set;}

    [Scaffoldcolumn (false)] public string Error {get; private set;}
                public string this[string ColumnName] {get {switch (columnName) { Case ' Name ': {if (string. IsNullOrEmpty (this.
                        Name) {return "' name ' is a required field ';
                    return null; Case "Gender": {if (string). IsNullOrEmpty (this.
                        Gender)) {return "' sex ' is a required field"; else if (!new string[] {"M", "F"}. Any (G =&Gt String.Compare (this.
                        Gender, G, true) = = 0)) {return ' ' sex ' must be ' M ', ' F ' one ';
                    return null; Case ' age ': {if (null = = this.
                        Age) {return "' ages ' is a required field"; else if (this. Age > 25 | | This.
                        Age </) {return "' ages ' must be between 18-25 years old";
                    return null;    
            } Default:return null;

 }
        }
    }
}

Four. Form validation of binding parameters ( to manually validate the parameters of a binding directly in the action) (rarely used)

1.ViewModel:

public class person
{
    [DisplayName (' name ']] public
    string Name {get; set;}

    [DisplayName ("Gender")]
    public string Gender {get; set;}

    [DisplayName ("Age")]
    public int? Age {get; set;}
}

2.Action in:

We validate this method by verifying the 3 attributes of a person object as a parameter, if the supplied data is not validated, We will call the current Modelstate Addmodelerror method to convert the specified validation error message to Modelerror save.

[HttpPost]
    Public ActionResult Index (person person)
    {
        Validate (person);

        if (! Modelstate.isvalid)
        {return
            View (person);
        }
        else
        {return
            Content ("input data passed validation");
        }
    

private void Validate (person person)
    {
        if (string). IsNullOrEmpty (person. Name)
        {
            modelstate.addmodelerror ("name", "' name ' is a required field ');
        }

        if (string. IsNullOrEmpty (person. Gender))
        {
            modelstate.addmodelerror ("Gender", "' Gender ' is a required field");
        }
        else if (!new string[] {"M", "F"}. Any (
            g => string.compare. Gender, G, true) = = 0))
        {
            modelstate.addmodelerror ("Gender", 
            "valid ' Gender ' must be ' M ', ' F ')");
        }

        if (null = = person. Age)
        {
            modelstate.addmodelerror (??, ' age ' is a required field);
        }
        else if (person. Age > 25 | | Person.
        Age < = {
            Modelstate.addmodelerror ("ages", "valid ' ages ' must be between 18-25 years of old")
        ;
    }
}

3.View in:

The extension method that calls Htmlhelper<tmodel> directly Editorformodel will be rendered as the person object of model in the form in edit mode

@using (Html.BeginForm ())
    { 
        @Html. Editorformodel ()
        <input type= "Submit" value= "Save"/>
    }

Five. Jquery Validate plug-in form validation (by using the Jaquery Validate plug-in for form validation) (for asp.net webform and asp.net mvc Two development methods)

method One: Ordinary form submits +jquery Validate authentication method:

1.Html:

<form id= "AddForm" method= "post" action= "/jqvalidate/addform" >
         <div>
             Name:
             <input type= " Text "Name=" txtname "id=" txtname/> <span class=
             "errormsg" > Location of error message placement </span>
             <br/>
             Age:
             <input type= "text" name= "Txtage"/> <span class=
             "errormsg" ></span>
             <br/ >
             Postal Code:
             <input type= "text" name= "Txtzipcode"/> <span class=
             "ErrorMsg" ></span>
         </div>
         <div>
             <input type= "Submit" value= "submitted"/>
         </div>
     </ Form>
2.JS Authentication:

<script src= "~/scripts/jquery-1.7.1.js" ></script> <script src= "~/scripts/jquery.validate.js" >
     </script> <script type= "Text/javascript" > $ (function () {//form validation formvalidate ();
 
     }); var formvalidate = function () {//Add custom checksum (ZIP code verification) JQuery.validator.addMethod ("Iszipcode", Function (VA
             Lue, Element) {var zipCode =/^[0-9]{6}$/; return this.optional (Element) | |
        (Zipcode.test (value));
 
         "Please fill in your zip code correctly");
                   $ ("#addForm"). Validate ({//#JQForm是form表单的ID rules: {txtname: {//ID of the form to validate Required:true,//Whether is required minlength:2,//Minimum length remote: "/jqvalidate/validat
                     Ename "//return True to receive error message}, Txtage: {required:true, Range: [A]}, Txtzipcode: {requiRed:true, Iszipcode:true,},}, messages: {//If the attribute is not incorrectly mentioned
                     , the default prompt txtname: {required: "Please enter the member name",////If the text of the prompt is not filled in when submitting MinLength: "The length of the member name can not be less than 2 bits",//if the input length is less than 2 hint of text remote: "User name repeat"}, t
                 Xtage: {required: "Age cannot be empty", Range: "Age range is 18~30"}, Txtzipcode: {required: "ZIP code cannot be empty"},}, Errorplace
             Ment:function (Error, Element) {//the position where the custom error message is placed Error.appendto (Element.next ("span"));
 },
         })
     };
 </script>

3. Add Custom Checksum:

http://huqiji.iteye.com/blog/2166986

Add custom checksum (ZIP code verification)
JQuery.validator.addMethod ("Iszipcode", function (value, Element) {
 var zipcode=/^[0-9]{6 }$/;
 return this.optional (Element) | | (Zipcode.test (value);
 }, "Please fill in your zip code correctly");

4. Remote Authentication:

A return value of true prompts for an error message, otherwise it is not prompted

Remote: "/jqvalidate/validatename",//returns TRUE, error message appears

Note If you do not pass the parameter, the default is to pass the current checksum value to the background check, if you want to pass in other parameters in this form (datatype must be a JSON type)

Remote: {//default will upload the current validated value to the background verification, if you need to transfer other parameters in the data to add the
   URL: "/jqvalidate/validatename",
   type: "POST",
   data: {"TestData": "TestName"},
   DataType: "JSON",//here The return type must be JSON
  }
Method II, AJAX form Ajax.beginform Submit +jquery Validate authentication method (Implementation of the successful validation of the asynchronous submission form)

1. Introduce JS:

<script src= "~/scripts/jquery-1.7.1.js" ></script>
@*ajax.beginform required js file *@ <script src=
" ~/scripts/jquery.unobtrusive-ajax.js "></script>
<script src=" ~/scripts/jquery.validate.js "> </script>

2. Create a form:

@using (Ajax.beginform ("AddForm", "Jqvalidate", New {}, new Ajaxoptions () {HttpMethod = "post", Onbegin = "Ajaxformonbeg In ", 
onsuccess =" Afteronsuccess ", onfailure =" Afteronfailure ", Updatetargetid =" Updatetargethiddenid "}, new {@id = "AddForm"})
     {
         <div>
             name:
             <input type= "text" name= "txtname" id= "txtname"/>
             < Span class= "errormsg" > Error message placement </span>
             <br/>
             Age: <input type= "
             text" name= "Txtage"/ >
             <span class= "errormsg" ></span>
             <br/>
             Postal code:
             <input type= "text" Name= " Txtzipcode "/>
             <span class=" errormsg "></span>
         </div>
         <div>
             < Input type= "Submit" value= "submitted"/>
         </div>
     }

3.js Verification: 2.3.4 One step of the same law


Method III, Non form form submission +jaquery Validate mode

Sometimes the page is not only form data, but also tables and other data, rather than through form forms are submitted to the background, but want to verify through the jquery.validate way. Then we can do it.

1.html:

<form>
         <div>
             name:
             <input type= "text" name= "txtname" id= "txtname"/> <span
             class = "ErrorMsg" > Error message placement </span>
             <br/>
             Age:
             <input type= "text" name= "Txtage
             "/> <span class= "errormsg" ></span>
             <br/>
             Postal code:
             <input type= "text" Name= "Txtzipcode "/>
             <span class=" errormsg "></span>
         </div>
         <div>
             <input type=" Button "Value=" submitted "onclick=" Javascript:btnsubmit (); "/>
         </div>
     </form>
2.js Authentication:

One method in the Jquery.validate is valid (), which is used to determine whether the form is validated, and whether the validation is legal.

<script type= "Text/javascript" > $ (function () {//form validation formvalidate ();
 
     }); var formvalidate = function () {//Add custom checksum (ZIP code verification) JQuery.validator.addMethod ("Iszipcode", Function (VA
             Lue, Element) {var zipCode =/^[0-9]{6}$/; return this.optional (Element) | |
         (Zipcode.test (value));
 
         "Please fill in your zip code correctly");
                     $ ("#addForm"). Validate ({//#JQForm是form表单的ID rules: {txtname: {//ID of the form to validate Required:true,//Whether is required minlength:2,//Minimum length remote: "/jqvalidate/
                 Validatename ",//returns TRUE, error message will appear}, Txtage: {range: [18, 30] 
                 }, Txtzipcode: {required:true, iszipcode:true, }, messages: {//If a property error is not prompted, the default prompt is used Txtname: {required: "Please enter the member name",//If the submission does not fill in the prompt text minlength: "The length of the member name can not be less than 2 digits",//if the loss In length less than 2 hint of text remote: "User name Repeat"}, Txtage: {requ
                     Ired: "Age cannot be empty", Range: "Age range is 18~30"}, Txtzipcode: { Required: "ZIP code cannot be empty",}, Errorplacement:function (error, Element) {
             The location where the custom error message is placed Error.appendto (Element.next ("span"));
 },
         })
     }; </script>
3. Click on the button to determine whether the Jaquery validate validation, through the back to the background to submit data, did not pass will appear error prompts.

     Non Submit button Submit Method
     var btnsubmit = function () {
         //Detect form Validation pass and form validation
         var validatestate = $ ("#addForm"). Valid ( );
         if (!validatestate) {return
             false;
         }
  
         Submit the data back to the table, of course, you can also pass the other data you want to submit
         $.ajax ({
             URL: "/jqvalidate/addform",
             type: "Post",
             dataType: "Text",
             data:{txtname:$ ("#txtName"). Val ()},
             success:function (data) {
                 alert (data);
             }
         );
         
     

Six. asp.net MVC asynchronous Form validation and asynchronous non-form verification: three methods http://www.csharpwin.com/dotnetspace/13578r5351.shtml

1, through the Ajax.beginform () method, return partial view display authentication information.
2, through the Jquery+html.beginform () method, return partial view display authentication information.
3. Through jquery, the JSON string is returned, and the JSON string contains partial views and validation information.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.