ASP. net mvc 4 Practice Study Note 6: verification,

Source: Internet
Author: User

ASP. net mvc 4 Practice Study Note 6: verification,

The content of this chapter "view model" is mentioned earlier and has not been explained in more detail. Go to the next chapter:

I. Server Verification:

Whether the client is verified or not, server-side verification should be performed. Because users may disable JavaScript or do unexpected things to bypass client authentication, server authentication is the last line of defense to protect data and prevent poor input. Some verification rules also need to be processed by the server. For example, the network topology may require that only the server can access some external resources required to verify the input.

1. Data Annotations verification: [This section also mentioned above]

The annotation attribute of Data Annotations not only controls verification, but also has some new template features, such as DisplayName and DataType annotation attributes. Annotation properties dedicated to control verification are listed in the following table:

The ValidationSummary extension method provides a summary list of verification errors, usually displayed at the top of the form. For validation errors of specific model attributes, you can use ValidationMessage and expression-based ValidationMessageFor methods.

The MVC verification engine places verification errors in ModelState and aggregates all existing errors into the IsValid attribute.

2. Extended ModelMetadataProvider:

The page corresponding to the Create action of the previous code is displayed as follows:

If you want DateAdded to be displayed as Date Added, you can use the DisplayNameAttribute annotation attribute settings. However, because displaying attribute names with spaces is a common requirement, we can implement this by extending the ModelMetadataProvider class.

ModelMetadataProvider abstract class:

1 public abstract class ModelMetadataProvider 2 {3 public abstract IEnumerable <ModelMetadata> GetMetadataForProperties (4 Object container, 5 Type containerType 6 ); // obtain the ModelMetadata 7 public abstract ModelMetadata GetMetadataForProperty corresponding to each attribute of the model (8 Func <Object> modelAccessor, 9 Type containerType, 10 string propertyName11 ); // obtain ModelMetadata 12 public abstract ModelMetadata GetMetadataForType (13 Func <Object> modelAccessor, 14 Type modelType15) for the specified attribute; // obtain ModelMetadata 16 for the specified model accessor and model Type}

To customize the display text of a specific attribute, we only need to override the CreateMetadata method of the DataAnnotationsModelMetadataProvider class:

 

1 namespace Guestbook 2 {3 public class ConventionProvider: partitions 4 {5 protected override ModelMetadata CreateMetadata (IEnumerable <Attribute> attributes, 6 Type containerType, 7 Func <object> modelAccessor, 8 Type modelType, 9 string propertyName) 10 {11 var meta = base. createMetadata (attributes, containerType, modelAccessor, modelType, propertyName); 12 if (meta. displayName = null) // Since the display name may be overwritten with the annotation attribute, we only modify the display name's behavior 13 {14 meta when it is not set. displayName = meta. propertyName. toSeparatedWords (); 15} 16 return meta; 17} 18} 19}

The ToSeparatedWords extension method divides Pascal-style case-sensitive identifiers into individual words:

 1 namespace Guestbook 2 { 3     public static class StringExtensions 4     { 5         public static string ToSeparatedWords(this string value) 6         { 7             if (value != null) 8                 return Regex.Replace(value, "([A-Z][a-z]?)", " $1").Trim(); 9             return null;10         }11     }12 }

Then modify the Global. asax file:

 1 namespace Guestbook 2 { 3     public class MvcApplication : System.Web.HttpApplication 4     { 5         protected void Application_Start() 6         { 7             AreaRegistration.RegisterAllAreas(); 8             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 9             RouteConfig.RegisterRoutes(RouteTable.Routes);10             BundleConfig.RegisterBundles(BundleTable.Bundles);11             ModelMetadataProviders.Current = new ConventionProvider();12         }13     }14 }

As shown in the following figure:

Ii. Client Verification:

1. Client verification preliminary:

To enable client verification, you must:

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

2) Add configuration in web. config:

<appSettings>    <add key="ClientValidationEnabled" value="true" />    <add key="UnobtrusiveJavaScriptEnabled" value="true" />  </appSettings>

3) add data label attributes as follows:

<input 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, the work seems to have been completed automatically, and you no longer need to do it yourself... Am I right?

2. Use RemoteAttribute:

This is a remote verification annotation property. Before a user submits a form, the server performs remote verification on the model attribute, displays an error message when a verification error occurs, and rejects the form submission. The advantage is that you can execute a variety of verification logic or the verification logic that cannot be implemented by the client, but such remote verification also affects performance, the verification process includes communication with the remote server, execution of the verification process, and feedback on the verification results. Take the Create action as an example:

1) Add the Age attribute, modify the view, and delete the database for convenience (because the table structure is changed ):

Namespace Guestbook. models {public class GuestbookEntry {public int Id {get; set;} [Required] public string Name {get; set;} [Required] [Remote ("IsNumberEven ", "Guestbook", ErrorMessage = "an even number is Required")] public int Age {get; set;} [Required] public string Message {get; set;} public DateTime DateAdded {get; set ;}}}

2) Add a method to the Controller:

public JsonResult IsNumberEven(int evenNumber)        {            return Json(evenNumber % 2 == 0, JsonRequestBehavior.AllowGet);        }

This action checks whether the value is an even number and returns a Boolean value encapsulated with JsonResult.

But why does it fail to respond when you click Submit after adding RemoteAttribute? Does MVC 5 not support this attribute?

3. Create a custom client validator:

Skip this section...

This chapter fails...

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.