Use MVC to build a class site-registration interface: Use of data annotations

Source: Internet
Author: User

This term WebProgramThe course design is a class site, and ASP. NET is used, so I decided to use ASP. NET MVC to complete this question.

First, the registration interface is complete:

To implement such a page is actually very simple, as long as there is a fieldset, the key is to verify the warning message.

MVC provides a lot of convenience for data annotation. To achieve the above effect, you only need to add data annotation to the attribute fields in the model:

  Public   Class  User {[hiddeninput (displayvalue = False  )]  Public   Int Userid { Get ;Set  ;} [Required (errormessage = "  The name cannot be blank!  "  )] [Stringlength (  160  )] [Displayname (  "  Name  "  )]  Public String name { Get ; Set ;} [Required (errormessage = "  The password cannot be blank!  "  )] [Stringlength (  160  )] [Displayname (  "  Password  "  )] [Datatype (datatype. Password)]  Public String password { Get ; Set ;} [Required (errormessage = "  Enter the password again!  "  )] [Stringlength (  160  )] [Displayname (  "  Confirm Password  "  )] [Datatype (datatype. Password)] [compare (  "  Password  " , Errormessage = " The password is inconsistent. Enter another password!  "  )]  Public String confirmpassword { Get ; Set  ;} [Required (errormessage = "  The phone number cannot be blank!  "  )] [Stringlength (  160  )] [Displayname (  "  Phone number "  )]  Public String phone { Get ; Set  ;} [Required (errormessage = "  Qq cannot be blank!  "  )] [Stringlength (  160  )] [Displayname (  "  Qq  " )]  Public String QQ { Get ; Set  ;} [Required (errormessage = "  Email cannot be blank!  "  )] [Stringlength (  160  )] [Regularexpression (  @"  [A-Za-z0-9. _ % +-] + @ [A-Za-z0-9.-] + [A-Za-Z] {2, 4}  " , Errormessage ="  Email is not valid  "  )] [Datatype (datatype. emailaddress)] [displayname (  "  Email  "  )]  Public String email { Get ; Set  ;} [Required (errormessage = "  The student ID cannot be blank!  " )] [Displayname (  "  Student ID  "  )]  Public   Long Number { Get ; Set  ;}} 

For more information, see my other blog: Workshop.
Even if we add data annotations to the attribute field of the model, this does not mean we can close the work.

Data annotation was originally used to provide server-side verification. However, with the development of client-side verification, the data annotation used on the model also provides client-side verification. Data annotation is very useful, which enables us to perform a lot of verificationCodeBut how is it done? When does verification happen?

By default, the MVC Framework performs the verification logic when the model is bound.

What is model binding? The generation of model binding comes from naming conventions: Elements in a view are named as input elements, and most of them match attribute names. Based on this fact, "conventions take precedence over configurations" will begin to play a role. When we pass in a model as a parameter in the action, MVC will call the default model binder (different models can register multiple model bindings, but in general, the default model binder can solve most of the problems ). When the Model binder sees that the input model contains parameters in a request, it will convert the value and move it into the model, it can even create a model to fill in! The so-called request is like a set of submitted forms. However, the model binder does not only search for a set of forms. It uses the value provider) in different regions of the request. It can view form sets, route data, and query strings.

The magic is that the model binder uses a basic data type, such as an int or a parameter that can be filled with it, just as we want to find the id value, you can input an int value, and then the model binder will find the desired value in the query string or route data.

The side effect of model binding is the model status. It records every value in the model and all errors associated with this attribute. Therefore, we can check the model status to see if the model is successfully bound.

After learning about the model binder, we understand that when the model binder uses the new value to update the Model attributes, all the validators of the model are obtained using the current model metadata. The model validators will find all verification features and execute the verification logic they contain, and then the model binder will capture all failed verification rules and put them into the model status. The built-in HTML auxiliary method can use the model State to change the display of the model in the view. Based on this fact, we can see how the error message is displayed in the view, as shown in the following code:

 
<%: HTML. validationmessagefor (model => model. Name) %>

In this way, we can display the corresponding error message next to the HTML control corresponding to each attribute in the view.
There are other methods, that is, we can get them first and then display all error messages in a certain area of the View:

 
<%: HTML. validationsummary (True) %>

If the parameter is set to true, error messages at the attribute level are hidden and only model-level errors are displayed. If it is false, the opposite is true:

This is definitely not easy to understand, so it is only suitable for the case where there are few verification fields.

The following is the controller:

 [Httppost] Public  Actionresult register (User user ){  If  (Modelstate. isvalid ){  //  Attempt to register the user  Membershipcreatestatus createstatus; membership. createuser (user. Name, user. Password, user. confirmpassword,  "  Question  " , "  Answer  " ,True , Null , Out  Createstatus );  If (Createstatus = Membershipcreatestatus. Success) {formsauthentication. setauthcookie (user. Name,  False   /*  Createpersistentcookie  */  );  Return Redirecttoaction ( " Index  " , "  Home  "  );}  Else  {Modelstate. addmodelerror (  ""  , Errorcodetostring (createstatus ));}}  //  If we got this far, something failed, redisplay form              Return View (User );} 

First, we must check whether the model binding is successful. This can be determined by checking whether the modelstate is valid, and modelstate can also return the failed attributes of the binding and related error messages.
After the model is successfully bound, it is an opportunity for membership to appear.

Membership is used to verify user creden。 and manage user settings. It is mainly used for user authentication. We add this user for the first time during registration, so we need to add this user in membership. Membershipcreatestatus is used to obtain the operation result of creating a user for membership. The createuser () method can store users with specified attribute values in the user storage area, and can specify a unique identifier, we do not need a unique identifier here, so we set it to null. After the user role is created successfully, we use forms authentication to use the user name as the authentication cookie and add it to the cookie set or URL of the response. It will be a big topic to discuss identity authentication, so here is just a brief introduction.

If the model binding fails, we need to add the failed binding error to modelstate. The code here is:

 
Modelstate. addmodelerror ("", Errorcodetostring (createstatus ));

Indicates that attribute-level verification is excluded because association errors and key values of specific attributes are not provided. You can also specify a specific attribute value so that the view does not display error messages related to this attribute because it has been added to modelstate, replace the message specified later.

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.