MVC Learning Series-Model verification extension, mvc series model verification

Source: Internet
Author: User

MVC Learning Series-Model verification extension, mvc series model verification

In MVC, front-end backend verification is implemented.

Front-end Verification. Steps:

Web. config must be enabled:

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

JS settings

Step 1: Introduce page js

@Scripts.Render("~/bundles/jqueryval")

Step 2: BundleConfig class, which must have

1  bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(2                         "~/Scripts/jquery.validate*"));

That is, these three js

Front-end verification, implemented in MVC:

Add some features to the Model in System. ComponentModel. DataAnnotations, such as Required range.

HtmlHelp in MVC analyzes these features and loads data-XX.

For example:

1   [Required]2   public string Gender { get; set; }
1  @Html.EditorFor(x => x.Gender)

Generated html

1 <input class = "text-box single-line" data-val = "true" data-val-required = "Gender field is required. "Id =" Gender "name =" Gender "type =" text "value =" ">

Then, automatically implement front-end Verification Based on the relevant JS.

Server Verification:

Implementation in mvc: some features are added to the Model in System. ComponentModel. DataAnnotations, such as Required range.

 1  [HttpPost] 2         public ActionResult CreateStudent(StudentViewModel model) 3         { 4  5             ModelState.AddModelError("A", "AAAAA"); 6             ModelState.AddModelError("B", "BBBBB"); 7             ModelState.AddModelError("C", "CCCCC"); 8             ModelState.AddModelError("D", "DDDDD"); 9 10             return View();11         }

Server-side verification is enabled during ModelBinder. At the same timeVerification Failure InformationPass the value to ModelState as a key-Value Pair

Error message presentation:

 @Html.ValidationSummary(false)

Indicates whether to hide the error message. false indicates that the error message is not hidden. true indicates that the error message is hidden.

1 @Html.ValidationMessageFor(x => x.Name)2 @Html.ValidationMessage("Name")

The first is the lamda expression, and the second is the general form. The role is the same.

They all indicate corresponding errors (the corresponding value is displayed based on the key)

 

 

Custom ValidationAttribut (server-side verification only)

1: For an attribute

New Class MyValidationAttribute inherits ValidationAttribute

1 public class MyValidationAttribute: ValidationAttribute 2 {3 public MyValidationAttribute () 4 {5 ErrorMessage = "The Name Must be Zhangsan"; 6} 7 public override bool IsValid (object value) 8 {9 if (value = null) 10 {11 return false; 12} 13 string result = value. toString (); 14 // determines whether a value is 15 if (string. isNullOrEmpty (result) 16 {17 return false; 18} 19 20 if (result = "Zhangsan") 21 {22 return true; 23} 24 return false; 26} 27}

Application:

1 public class StudentViewModel2     {3         public string ID { get; set; }4         [MyValidationAttribute]5         public string Name { get; set; }6         [Required]7         public string Gender { get; set; }8     }

View:

1 <div> 2 @ using (Html. beginForm () 3 {4 @ Html. validationSummary (false) 5 <fieldset> 6 <legend> UserInfo </legend> 7 <div class = "editor-label"> 8 @ Html. labelFor (x => x. name) 9 </div> 10 <div class = "editor-field"> 11 @ Html. editorFor (x => x. name) 12 @ Html. validationMessageFor (x => x. name) 13 @ Html. validationMessage ("Name") 14 </div> 15 16 <div class = "editor-label"> 17 @ Html. labelFor (x => x. gender) 18 </div> 19 <div class = "editor-field"> 20 @ Html. editorFor (x => x. gender) 21 @ Html. validationMessageFor (x => x. gender) 22 </div> 23 </fieldset> 24 <input type = "submit" value = "submit"/> 25} 26 </div>

Effect:

2: complex business logic

Class StudentViewModel inherited interface IValidatableObject

 public class StudentViewModel: IValidatableObject    {        public string ID { get; set; }        [MyValidationAttribute]        public string Name { get; set; }        [Required]        public string Gender { get; set; }        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)        {            if (!string.IsNullOrEmpty(Name))            {                if (Name=="Zhangsan" && Gender=="Nan")                {                    yield return new ValidationResult("Zhangsan and Gender is Nan,Which is wrong!");                }            }        }    }

:

 

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.