ASP. NET MVC Model validation (i)

Source: Internet
Author: User

ASP. NET MVC Model Validation ( a ) Preface

The first part of the model binding is described in general, from the beginning of this chapter into the Model validation section, this is actually a series of model binding is often accompanied by validation. will also explain in the later space the MVC framework Model validation mechanism, as well as some model validation of the way to explain, this chapter is just a simple example of space, for the basic friends can skip directly (can not delay everyone time).

Model Validation
    • Model validation Simple Application Example
    • Modelvalidator using the build process
    • Custom Implementation Defaultmodelbinder to verify
    • Custom Modelvalidatorprovider and Modelvalidator
    • Validationattribute attribute classes use
    • Custom Validationattribute An example implementation of an attribute class

Model Validation Simple Application Example

ViewModel the definition

First look at the definition of ViewModel, model verification is of course inseparable from model, example code 1-1.

Code 1-1

namespacemvcapplication.models{/// <summary>    ///viewmodel-User Registration Information/// </summary>     Public classregistrationinformation { Public stringID {Get;Set; }  Public stringUserID {Get;Set; }  Public stringPassword1 {Get;Set; }  Public stringPassword2 {Get;Set; }  Public stringName {Get;Set; } }}

In code 1-1, the registrationinformation type is defined to contain some of the properties of the registration information.

Configuring the Environment

With ViewModel, we need a data presentation page, we define a Modelvalidatorcontroller controller, and in which we define the index () method, which displays the information that the page provides to the user for registration. Example code 1-2.

Code 1-2

namespace mvcapplication.controllers{    publicclass  Modelvalidatorcontroller:controller    {        public  actionresult Index ()        {            return View (new  models.registrationinformation ());     }}}

Then we'll define the code for the page, which is the index view of the index () method, example code 1-4.

Code 1-3

@model mvcapplication.models.registrationinformation@{viewbag.title = "Index";}<H2>Index</H2>@using (Html.BeginForm ("Modelvalidator", "Modelvalidator")) {<P>User Registration ID: @Html. Editorfor (m=>m.id)</P>    <P>User name: @Html. Editorfor (M=>m.userid)</P>    <P>Login password: @Html. editorfor (M=>m.password1)</P>    <P>Enter the domain password again: @Html. Editorfor (M=&GT;M.PASSWORD2)</P>    <inputtype= "Submit"value= "Submit" />}

The form in code 1-3 defines the Modelvalidator () method that points to the Modelvalidatorcontroller controller, and I'm sorry I didn't separate the named well-defined areas.

Now that code 1-3 points to the Modelvalidator () method, we need to modify the code in sample code 1-2 to add sample code 1-4 to sample code 1-2.

Code 1-4

 Publicactionresult modelvalidator (registrationinformation reginfo) {if(string. IsNullOrEmpty (reginfo.id) | | Reginfo.id = ="")            {                 This. Modelstate.addmodelerror ("ID","Please enter Id,id cannot be empty!"); }            if(string. IsNullOrEmpty (Reginfo.userid) | | Reginfo.userid = ="")            {                 This. Modelstate.addmodelerror ("UserID","Please enter user account, user account cannot be empty! "); }            if(string. IsNullOrEmpty (reginfo.password1) | | Reginfo.password1 = ="")            {                 This. Modelstate.addmodelerror ("Password1","Please enter the login password, login password can not be empty!"); }            if(string. IsNullOrEmpty (REGINFO.PASSWORD2) | | Reginfo.password2 = ="")            {                 This. Modelstate.addmodelerror ("Pssword2","Please enter the password again, the password cannot be empty!"); }            if(!string. IsNullOrEmpty (Reginfo.password2)) {if(Reginfo.password2! =reginfo.password1) { This. Modelstate.addmodelerror ("Password2","Please re-enter the password, different from the last password entered"); }            }            returnView (Reginfo); }

In code 1-4 is to verify the model, you can see that is a simple validation, the judge cannot be empty, the input of the password to the same two.

1-4 is already the model binding, the system has been implemented into the Controller method inside, and in the model validation, and the real validation is in the model binding phase, this part of the content will be explained in the next chapter.

Let's take a look at the view definition for the Modelvalidator () method, code 1-5.

Code 1-5

@model mvcapplication.models.registrationinformation@{viewbag.title = "Modelvalidator";}<H2>Modelvalidator</H2>@Html. ValidationSummary ()<P>User Registration ID: @Html. editorfor (M = m.id)</P><P>User name: @Html. editorfor (M = m.userid)</P><P>Login password: @Html. editorfor (M = m.password1)</P><P>Enter the domain password again: @Html. editorfor (M = m.password2)</P>

In code 1-5, the Html.validationsummary () method is called, and the purpose of this view helper is to generate HTML code for the exception information generated by our model validation.

Now let's look at the project run 1

Figure 1

Based on the validation in the Modelvalidator () method, we deliberately enter this, and then look at the Modelvalidator page after clicking "Submit", Figure 2

Figure 2

Some friends may say that the display of the non-common sense, where there is a hint of the wrong information displayed in the above, can be modified, modify code 1-5, example code 1-6.

Code 1-6

@model mvcapplication.models.registrationinformation@{viewbag.title = "Modelvalidator";}<H2>Modelvalidator</H2><P>User Registration ID: @Html. editorfor (M = m.id) @Html. Validationmessagefor (m=>m.id)</P><P>user name: @Html. editorfor (M = M.userid) @Html. Validationmessagefor (M=>m.userid)</P><P>login Password: @Html. editorfor (M = m.password1) @Html. Validationmessagefor (m=>m.password1)</P><P>Enter the domain password again: @Html. editorfor (M = m.password2) @Html. Validationmessagefor (M=>M.PASSWORD2)</P>

After the modification we still use the previous test data to see the final result Figure 3.

Figure 3

A simple demonstration is here, and the next one explains where and how the model verification is located in the MVC framework and the approximate process.

Jinyuan

Source: http://www.cnblogs.com/jin-yuan/

This article is copyrighted by the author and the blog Park, welcome reprint, but without the consent of the author must retain this statement, and on the article page

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.