"ASP 4 Practical" study Note 6: Verify

Source: Internet
Author: User

This chapter of the book "View Model" is mentioned in the previous section and has not been further explained so skip, go to the next chapter:

First, server-side validation:

Server-side validation should be performed regardless of client authentication or not. Because users might disable JavaScript or do something unexpected to bypass client-side validation, server validation is the last line of defense to protect data and prevent poor input. Some validation rules also require server-side processing, such as a network topology that may require only the server to access certain external resources that are required to authenticate the input.

1.Data Annotations Verification: [also mentioned in the previous section]

The annotation properties of Data annotations not only control validation but also some of the new template features, such as DisplayName and datatype annotation properties. The annotation properties that are designed to control validation are the following table:

The ValidationSummary extension method provides a summary list of validation errors, usually displayed at the top of the form. For validation errors for a particular model property, you can use the validationmessage and expression-based validationmessagefor methods.

The MVC validation engine places validation errors in Modelstate and aggregates any existing errors into the IsValid property.

2. Extended Modelmetadataprovider:

The previous code's create action corresponds to the page display such as:

If we want dateadded to appear as a date Added, you can use the Displaynameattribute annotation property setting. But because displaying property names with word spaces is a common requirement, we can extend the Modelmetadataprovider class implementation.

Modelmetadataprovider Abstract class:

1  Public Abstract classModelmetadataprovider2 {3      Public AbstractIenumerable<modelmetadata>Getmetadataforproperties (4 Object Container,5 Type Containertype6);//gets the modelmetadata that corresponds to each property of the model7      Public AbstractModelmetadata Getmetadataforproperty (8Func<object>Modelaccessor,9 Type Containertype,Ten     stringPropertyName One);//gets the modelmetadata of the specified property A      Public AbstractModelmetadata Getmetadatafortype ( -Func<object>Modelaccessor, - Type Modeltype the);//gets the modelmetadata of the specified model accessor and model type -}

In order to customize the display text for a particular property we only need to rewrite the Createmetadata method of the Dataannotationsmodelmetadataprovider class:

1 namespaceGuestbook2 {3      Public classConventionprovider:dataannotationsmodelmetadataprovider4     {5         protected OverrideModelmetadata Createmetadata (ienumerable<attribute>attributes,6 Type Containertype,7func<Object>Modelaccessor,8 Type Modeltype,9             stringPropertyName)Ten         { One             varMeta=Base. Createmetadata (attributes, Containertype, Modelaccessor, Modeltype, PropertyName); A             if(Meta. DisplayName = =NULL)//because the display name may be overridden with the annotation property, we only modify its behavior when the display name is not set -             { -Meta. DisplayName =Meta. Propertyname.toseparatedwords (); the             } -             returnMeta; -         } -     } +}

The Toseparatedwords extension method is to divide the Pascal-style case identifiers into individual words:

1 namespaceGuestbook2 {3      Public Static classstringextensions4     {5          Public Static stringToseparatedwords ( This stringvalue)6         {7             if(Value! =NULL)8                 returnRegex.Replace (Value,"([a-z][a-z]?)"," $"). Trim ();9             return NULL;Ten         } One     } A}

Then modify the Global.asax file:

1 namespaceGuestbook2 {3      Public classMvcApplication:System.Web.HttpApplication4     {5         protected voidApplication_Start ()6         {7 Arearegistration.registerallareas ();8 filterconfig.registerglobalfilters (globalfilters.filters);9 routeconfig.registerroutes (routetable.routes);Ten bundleconfig.registerbundles (bundletable.bundles); One             modelmetadataproviders.current = new Conventionprovider (); A         } -     } -}

Now the run is as shown:

Second, client authentication:

1. Client validation Preliminary:

In order to enable client-side validation, you need to:

1) Add Jquery.js, jquery.validate.js, jquery.validate.unobtrusive.js references;

2) Add the configuration in Web. config:

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

3) Add the data tag property as follows:

<class= "Text-box single-line"  data-val= "true"  data-val-required= "The Name field is required." ID = "Name" name = "Name" type = "text" value ="" />

But in MVC 5, these jobs seem to be automated, and no longer need to do it yourself ... Did I say that, right?

2. Use Remoteattribute:

This is a remote validation annotation property. Remote validation of the model properties is performed on the server side before the user submits the form, and an error message is displayed with a validation error and the form is rejected. The benefit is that you can perform rich validation logic or validation logic that the client cannot implement, but this remote validation can also affect performance because it includes communication with the remote server, execution of the validation process, and feedback on the results of the validation during validation. Take the Create action as an example:

1) Add the Age property, modify the view, and make it easy to delete the database (because the table structure changes):

namespaceguestbook.models{ Public classGuestbookentry { Public intId {Get;Set; } [Required] Public stringName {Get;Set; }        [Required] [Remote ( "Isnumbereven", "guestbook", errormessage = "An even number must be entered")]  Public intAge {Get;Set; } [Required] Public stringMessage {Get;Set; }  PublicDateTime dateadded {Get;Set; } }}

2) Add a method to the controller:

 Public Jsonresult isnumbereven (int  evennumber)        {            return20 , Jsonrequestbehavior.allowget);        }

This action checks whether this value is an even number and returns a Boolean value that is encapsulated in Jsonresult.

But why did you add Remoteattribute and click Submit to not react? IS MVC 5 not supported for this property?

3. Create a custom client validator:

This section is not understood, temporarily skipped ...

This chapter good failure ...

"ASP 4 Practical" study Note 6: Verify

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.