MVC validation (combined use of model annotations and non-intrusive scripting)

Source: Internet
Author: User

Tags created @HtmlHrlper way, some properties are automatically generated, some of which are about validating

Example:

Model annotations

After the model annotation, MVC validation, including the foreground client, background server authentication, MVC has all been included, even if the user disables JavaScript on the client, the server will also verify the illegal operation, the current premise is that the model entity identified the case of annotations.

To be able to properly verify the validity of non-null, the following steps must be performed (prerequisites):

1. The required attribute must be added to each type of entity, but the properties of the numeric type are added by default.

2. The following script must be imported on the view:

<Scriptsrc= "~/scripts/jquery-1.7.1.js"></Script>   <Scriptsrc= "~/scripts/jquery.validate.js"></Script><Scriptsrc= "~/scripts/jquery.validate.unobtrusive.js"></Script>--Non-embedded script

3. The properties in the configuration file are configured as follows:

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

MVC defaults to the style that comes with it:

<href= "~/content/site.css"  rel= "stylesheet"/>

Key namespaces:

using System.ComponentModel.DataAnnotations; using System.ComponentModel; using SYSTEM.WEB.MVC;

Working with instances

One, non-null verification

Marking on attributes:

  [Required (errormessage= "cannot be Empty")]  public string Dusername {get; set;}

Add @html.validationmessagefor to the View Creation tab, which is a hint when a validation error occurs, essentially a span tag

  @Html. Textboxfor (d=>d.dusername)  @Html. Validationmessagefor (D=>d.dusername)

Second, the length of the Constraint text box input

Key code:

[Stringlength (minimumlength = 4, errormessage = "name can only be between 4 and 10")]public string Dusername {get; set;}

Add a description to the control of the form item

Key code:

[DisplayName (" name ")]  Public string Get set; }

The View code plus the corresponding code:

@html.displaynamefor (d=>d.dusername)

Corresponding effect:

Four, the bounds of the value of the integer constraint, marking the attribute as follows:

[Range(100,1000,errormessage=min. $100, maximum donation of 1000 Yuan )]

Five, ensure that the text box input is the same as the other (can be used for two password input consistency)

[Compare ("Pwd1", errormessage= "two times input password inconsistent")]

The first parameter is the name of the property to match

Vi. using regular expressions

[RegularExpression ("\\d+", errormessage= "password must be a pure number")]

Vii. Custom Type Form labels

Background code:

[DataType (datatype.emailaddress)]        [DisplayName (" e-mail ")]          Public string Get set; }

Front desk use:

  @Html. Displaynamefor (d=>d.email)  ----hint text  @Html. Editorfor (d=>d.email)    -----Custom Type Label For Email format  @Html. Validationmessagefor (d=>d.email)  ---Tip error message label

Enter the wrong message here, the default is English, need to change the file can be changed to Chinese, modify the plot:

Eight, remote annotation property pairs, text box input, through the AJAX connection database, to determine the validity (this method is validated with the AJAX Connection database)

Example: Registration can be used to check whether the user name has been used, the magic effect:

Note: Remote is validated through an AJAX request, in order to prevent the cache from being written as a POST request

Marking:

[Remote ("checkusername","donation", errormessage="  user name already exists ", httpmethod="post")]   

Checkusername (action method)

Donation (Controller name)

The action method works with examples:

[HttpPost] PublicActionResult Checkusername () {//1. Get the value of the check            stringuname = request["Dusername"]; //2. Connection Database judgmentDonationentities db=Newdonationentities (); varModel=db. Donationdetail.firstordefault (d=>d.dusername==uname); if(model!=NULL&&model.dusername==uname) {                returnContent ("false"); }            returnContent ("true"); }

Nine, background verification

MVC verifies that the client needs to rely on the JS script file, if the user disables JavaScript in the browser,

Then I can use the following countermeasures in the background.

// indicates whether the property in the entity object that is labeled with the attribute label is valid, and if one of the rules returns false            if (modelstate.isvalid==false)            {                /*                  Returns a view for validation failure the corresponding prompt message                 * The view requires @Html. Validateionsummry                 (true) label with */                 modelstate.addmodelerror (""," entity validation failed ");                 return View ();            }

MVC validation (combined use of model annotations and non-intrusive scripting)

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.