Detailed description of ASP. net mvc Model verification, asp. netmvc

Source: Internet
Author: User
Tags what is asp

Detailed description of ASP. net mvc Model verification, asp. netmvc

ASP. one of the best advantages of NET mvc is that it supports Model verification. This feature makes it easy for you to use the feature in the field for annotation Conventions when defining the Model, you can also perform manual verification in the code. The following describes how to implement ASP. net mvc Model verification in multiple ways.

I. What is ASP. NET MVC Model verification?

First, we define a Model class to be used, Appointment. cs:

 1 using System;  2 using System.ComponentModel.DataAnnotations;  3   4 namespace ModelValidation.Models {  5     public class Appointment {  6   7         public string ClientName { get; set; }  8   9         [DataType(DataType.Date)] 10         public DateTime Date { get; set; } 11  12         public bool TermsAccepted { get; set; } 13     } 14 } 

The Date type of the above Appointment field is defined as the Date type, and the System is used. componentModel. in the DataAnnotations namespace, the field of the Model annotation is of the date type. If an invalid date Model is input, the verification is invalid.

Add the following style to site.css to mark incorrect input items:

1 .input-validation-error { 2     border: 1px solid #f00; 3     background-color: #fee; 4 }

Create a view and use MakeBooking. cshtml to input information:

 1 @model ModelValidation.Models.Appointment  2 @{  3     ViewBag.Title = "Make A Booking";  4 }  5 

Finally, add the following two actions to HomeController:

public ViewResult MakeBooking(){    return View();}[HttpPost]public ViewResult MakeBooking(Appointment appt){    if (ModelState.IsValid)    {        return View("Completed", appt);    }    else    {        return View();    }}

Check/Home/MakeBooking for the following results:

The Appointment Date input box is red, indicating that the input is invalid. Let's take a look at this input style class: "input-validation-error text-box single-line", and at the beginning it was: "text-box single-line" is much better. "input-validation-error", this is why we need to define a style named "input-validation-error" at the beginning. In other words, by default, when the MVC Model field verification fails, a css class "input-validation-error" will be added to the input items on the input page.

2. Use System. ComponentModel. DataAnnotations to annotate the Model Field

The preceding example shows how to use [DataType (DataType. date)] to specify that the field must be of the Date type, and DataType is of the enumeration type. You can select any type to specify your Model field. For example:

In fact, System. ComponentModel. DataAnnotations also provides us with many other verification rules. Commonly used:

[Required]: Required field

[RegularExpression ("xx"): Regular Expression

These are the classes defined in the System. ComponentModel. DataAnnotations namespace. The following examples are common classes used for Model Verification:

  • CompareAttribute provides two attributes for comparison.
  • CreditCardAttribute specifies that the data field value is a credit card number.
  • CustomValidationAttribute specifies a custom verification method to verify an instance of an attribute or class.
  • DataTypeAttribute specifies the name of the additional type to be associated with the data field.
  • DisplayAttribute provides a common feature that allows you to specify localized strings for the types and members of entity segmentation classes.
  • EmailAddressAttribute confirms an email address.
  • MaxLengthAttribute specifies the maximum length of the array or string data allowed in the attribute.
  • MinLengthAttribute specifies the minimum length of the array or string data allowed in the attribute.
  • PhoneAttribute uses the regular expression of the phone number to specify the data field value as a correct phone number.
  • RangeAttribute specifies the Numerical range constraint of the data field value.
  • RegularExpressionAttribute specifies that the data field value in ASP. NET Dynamic Data must match the specified regular expression.
  • RequiredAttribute specifies the value of the required data field.
  • UrlAttribute provides URL verification.
3. Manually verify an MVC Model explicitly

In addition to System. componentModel. in addition to specifying the Model verification rules for classes under DataAnnotations, we can also manually verify explicitly manually verifying the validity of an MVC Model in the program. Next we will remove the DataAnnotations added before Appointment. The Code is as follows:

1 public class Appointment2 {3     public string ClientName { get; set; }4  5     public DateTime Date { get; set; }6  7     public bool TermsAccepted { get; set; }8 } 

At this time, we will change the acceptance of the input Action MakeBooking to manually determine whether the Model field is legal:

 1 [HttpPost] 2 public ViewResult MakeBooking(Appointment appt) 3 { 4   5     if (string.IsNullOrEmpty(appt.ClientName)) 6     { 7         ModelState.AddModelError("ClientName", "Please enter your name"); 8     } 9  10     if (ModelState.IsValidField("Date") && DateTime.Now > appt.Date)11     {12         ModelState.AddModelError("Date", "Please enter a date in the future");13     }14  15     if (!appt.TermsAccepted)16     {17         ModelState.AddModelError("TermsAccepted", "You must accept the terms");18     }19  20     if (ModelState.IsValid)21     {22         return View("Completed", appt);23     }24     else25     {26         return View();27     }28 }

The preceding figure shows that the values of each field in the Action method are verified manually to meet the requirements. If the verification fails, ModelState is called. addModelError is added to the Model verification error message. This AddModelError has two parameters: the first is the verified field, and the second is the text to display the error message prompt. After verifying each field, call ModelState. IsValid to determine whether the result after Model verification is valid. If one field fails verification or ModelState. AddModelError and ModelState. IsValid are called, false is returned.

 

4. the MVC Model verification error message 4.1 is displayed on the page, and the MVC Model verification error message is displayed in summary form.

In the above example, when the verification fails, the text prompt is not displayed except the text box turns red. In fact, it is easy to display the MVC Model verification error information on the page. You only need to call @ Html. ValidationSummary () in the view.

@model MVCModelBindingDemo.Models.Appointment@{    ViewBag.Title = "Make A Booking";}

Similarly, if we do not input anything on the/Home/MakeBooking page, the results will be displayed after direct submission:

Let's check the Html source code generated by @ html. ValidationSummary (), for example:

The generated verification error message uses a div with the style "validation-summary-errors". The error items are listed by ul and li.

The following describes several parameter overload versions of the ValidationSummary () method:

  • Html. ValidationSummary (): Generate and output all verification error messages.
  • Html. ValidationSummary (bool): If bool is true, only the model-level error message is displayed, that is, the verification information registered through ModelState. AddModelError. If bool is false, all verification error messages are generated.
  • Html. ValidationSummary (string): displays a text before generating and outputting all verification error messages.
    Html. ValidationSummary (bool, string): displays a text before generating the verification error message. If bool is also true, only the model-level error message is displayed.

 

4.2 Display verification information for each Property-Level

In addition to displaying the MVC Model verification error information in the form summarized above, we can also display the verification information in each Property-Level. Property-Level verification information is the verification information we have registered through ModelState. AddModelError. Next let's change the/Home/MakeBooking View File. The modified content is as follows:

 1 @model MVCModelBindingDemo.Models.Appointment 2 @{ 3     ViewBag.Title = "Make A Booking"; 4 } 5 

We can see that @ Html. ValidationSummary () is removed, and the verification information of the corresponding field @ Html. ValidationMessageFor is added to the end of each field. The verification result is as follows:

 

 

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.