ASP. NET MVC Model validation (c)

Source: Internet
Author: User

ASP. NET MVC Model Validation (c) Preface

In the previous article, where the default model validation is verified in the MVC framework, and the internal execution of the Defaultmodelbinder type, you can see that the default model validation is performed in the specific method, and the topic of this article is to simulate the default implementation, A custom model binder inherits from the Defaultmodelbinder type and overrides some important methods.

Model Validation
    • Model Validation Simple Application Example
    • Modelvalidator using the build process
    • Custom Implementation Defaultmodelbinder Validation
    • customizing Modelvalidatorprovider and Modelvalidator
    • Validationattribute Attribute class use
    • Example implementations of custom Validationattribute attribute classes

Custom Implementation Defaultmodelbinder Validation

The example that is used here is to modify the example from the ASP. NET MVC Model validation (a), so there is nothing more to say and begin to paste the code directly.

The first is the definition of ViewModel, code 1-1.

Code 1-1

namespacemvcapplication.models{ Public classregistrationinformation { Public stringID {Get;Set; }  Public stringUserID {Get;Set; }  Public stringPassword1 {Get;Set; }  Public stringPassword2 {Get;Set; }  Public stringName {Get;Set; } }}

Definition of the controller, code 1-2:

Code 1-2

    Public class Modelvalidatorcontroller:controller    {        public  actionresult Index ()        {            return View (new  Models.registrationinformation ());        }          Public actionresult modelvalidator (registrationinformation reginfo)        {            return  View (reginfo);        }    }

The Controller method corresponds to the view definition, code 1-3:

Code 1-3-1

Index view

@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>    <P>Name: @Html. Editorfor (M=>m.name)</P>    <inputtype= "Submit"value= "Submit" />}

Code 1-3-2

Modelvalidator View

@model mvcapplication.models.registrationinformation@{viewbag.title = "Modelvalidator";}<H2>Modelvalidator</H2>@Html. ValidationSummary (True)<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><P>Name: @Html. Editorfor (M=>m.name)</P>

As shown earlier, the example shows the required definition, and this time the runtime will find that it is just a page pass and nothing happens. Now let's define a custom model binder that inherits from the Defaultmodelbinder type.

Code 1-4

 Public classMycustomdefaultmodelbinder:defaultmodelbinder {protected Override voidSetProperty (ControllerContext controllercontext, Modelbindingcontext BindingContext, PropertyDescriptor PropertyDescriptor,Objectvalue) {            Base.            SetProperty (ControllerContext, BindingContext, PropertyDescriptor, value); Switch(propertydescriptor.name) { Case "ID":                    if(string. IsNullOrEmpty ((string) value) | | (string) Value = ="") {BindingContext.ModelState.AddModelError ("ID","Please enter Id,id cannot be empty!"); }                     Break;  Case "UserID":                    if(string. IsNullOrEmpty ((string) value) | | (string) Value = ="") {BindingContext.ModelState.AddModelError ("UserID","Please enter user account, user account cannot be empty! "); }                     Break;  Case "Password1":                    if(string. IsNullOrEmpty ((string) value) | | (string) Value = ="") {BindingContext.ModelState.AddModelError ("Password1","Please enter the login password, login password can not be empty!"); }                     Break;  Case "Password2":                    if(string. IsNullOrEmpty ((string) value) | | (string) Value = ="") {BindingContext.ModelState.AddModelError ("Pssword2","Please enter the password again, the password cannot be empty!"); }                     Break;  Case "Name":                     Break; }        }        protected Override voidonmodelupdated (ControllerContext controllercontext, Modelbindingcontext bindingcontext) {Base.            Onmodelupdated (ControllerContext, BindingContext); Models.registrationinformation Reginfo= Bindingcontext.model asmodels.registrationinformation; if(bindingcontext.modelstate["Password1"]. Errors.Count = =0&& bindingcontext.modelstate["Password2"]. Errors.Count = =0)            {                if(Reginfo.password1! =reginfo.password2) {bindingContext.ModelState.AddModelError ("Password2","Please re-enter the password, different from the last password entered"); }            }            if(string. Compare (Reginfo.name,"Jinyuan",true)==0) {BindingContext.ModelState.AddModelError ("","The name you entered is illegal, change it now or check the water meter"); }        }    }

In code 1-4, we rewrite the SetProperty () method, from the knowledge in the previous article, that this method is traversed in the collection of PropertyDescriptor types, so that each time inside the method is only a model property, and in SetProperty ( The model validation logic inside the method is the same as the ASP. NET MVC Model validation (a).

In the Onmodelupdated () method, we first get an instance of the ViewModel type defined in example code 1-1, where some friends may ask why they are not used in the SetProperty () method, Instead, the validation is done using parameters of type PropertyDescriptor, because the SetProperty () method does not have a full assignment to ViewModel, so it cannot be used as a direct fetch of the instance. Then the above said, after this, from the current binding context of the Modelstate property to determine whether the password 1 and password 2 has a property validation level error message, if not, they will be validated equivalent, as shown in the code above, When I verify the name, I add the error message with the key value "", which means that the default is the model level validation error message.

All required validations are done, register our custom binders into the system, and add code 1-5 to the Application_Start () in the Global.asax file.

Code 1-5

ModelBinders.Binders.Add (typeofnew Binders.mycustomdefaultmodelbinder ());

Finally, let's take a look, figure 1 represents the page initially displayed, after I enter a portion of the information, after clicking Submit page will jump to Figure 2, and after the completion of verification shows the validation error message.

Figure 1

Figure 2

You can try it out here and explain a way to verify that the MVC framework provides us with some of the types of serious used to perform validation, as well as some simple examples, so that we don't use the model binder to perform validation, and it looks like the binder is a bit of a goof.



Jinyuan

Source: http://blog.csdn.net/jinyuan0829

This article is copyrighted by the author and Csdn, 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.