ASP. net mvc 2 Model Verification

Source: Internet
Author: User

[Original address] ASP. net mvc 2: Model Validation
[Original article publication date] Friday, January 15,201 0 AM

In addition to blogging, I also use Twitter to publish short posts and share links. Please passTwitter.com/scottguFollow me.]

This is the second article in my post series for ASP. net mvc 2 to be released. This blog post will discuss some improvements in ASP. net mvc 2 verification.

ASP. net mvc 2 Verification

Verification of user input and mandatory business rules/logic are the core requirements of most web applications. ASP. net mvc 2 contains a bunch of new features, significantly simplifying user input verification and forcible implementation of verification logic in model/view models. These features are designed in this way to verify the logicAlwaysYou can also execute the code on the client using JavaScript. The authentication facilities and features in ASP. net mvc 2 are designed:

1) developers can easily use dataannotation built into the. NET Framework to verify support. Dataannotation provides a very simple way to use the leastCodeAdd verification rules as declared on objects and attributes.

2) developers can integrate their own verification engines or use existing verification frameworks, such as the castle validators or entlib validators. ASP. net MVC 2 is designed to take advantage of the new ASP. net MVC 2 validation facility (including client verification, model binding verification, etc.) while simplifying the insertion of any type of verification architecture.

This means that it is extremely easy to enable verification in common application scenarios, while maintaining excellent flexibility for more advanced scenarios.

Use ASP. net mvc 2 and dataannotation to enable verification

Let's demonstrate a simple crud scenario in ASP. net mvc 2 and use the new built-in dataannotation to verify the support. Specifically, let's implement a "CREATE" form to allow users to input friends' data:

We want to ensure that the input information is valid before it is saved to the database. If it is invalid, an appropriate error message is displayed:

We want to make this verification happen both on the server side and on the client side (through JavaScript. We also want to ensure that our Code complies with the dry principle (don't repeat yourself, do not repeat ourselves), which means we should implement verification rules in one place and then make our controller, the action method and view to fulfill this commitment.

Below, I will use vs 2010 and ASP. NET MVC 2 to implement the above scenario. You can also use vs 2008 and ASP. net mvc 2 to achieve the same scenario.

Step 1: Implement friendscontroller (not verified at the beginning)

First, add a simple "person" class in a new ASP. net mvc 2 project, as shown below:

It has four attributes (C #'s automatic attributes are supported, and VB also supports automatic attributes in vs 2010, ah !).

Then, add a "friendscontroller" Controller class in the project to display two "CREATE" Action methods. The first action method is in/Friends/createCalled when a URL's HTTP-GET request comes in, it displays a blank form that is used to input personal data. The second action method is in/Friends/createCalled when the URL's HTTP-POST request comes in. It maps the submitted form input to a person object and verifies that no binding error occurs. If it is legal, in the end, the data will be stored in the database (We will implement related database work later in this tutorial ). If the submitted form input is invalid, the action method will re-display the form with an error:

After implementing the controller, you can right-click one of the action methods in Visual Studio and select the "add view" command to bring up the "add view" dialog box. Select the "Create" view that automatically generates the input object as person:

Visual Studio then generates a create. aspx view file containing the Framework Code (scaffolded) in the \ views \ friends \ directory of our project. Note that the following uses the new strong HTML helper method in ASP. net mvc 2 (which facilitates better support for intelliisense and compile-time checks ):

Now, when we run the application/Friends/createURL, we will get a blank form that can input data:

However, because we haven't implemented any verification in the application, no one can block us from typing fake input in the form and submitting it to the server.

Step 2: Use dataannotation to enable verification

Now, let's update the application and execute some basic input verification rules. We will implement these rules on our person model object, andNoImplemented in the Controller or view. The benefit of implementing these rules on the person object is that this will ensure that these verification will be executed in any scenario where the person object is used in the application (for example, if an editing scenario is added later ). This will help ensure that we keep the code dry and avoid repeating these rules in multiple places.

ASP. net MVC 2 allows developers to easily add declarative verification features on the model or view model class, and then ASP. net MVC is automatically executed when model binding is performed in an application. To look at the example, Let's update the person class and add several verification features to it. In this way, add "system. componentmodel. the "using" statement of the dataannotations namespace is then decorated with [required], [stringlength], [range], and [regularexpression] Verification features (these features are implemented in that namespace ):

Note: We explicitly specified the error message string above. You can also define them in the resource file, or perform localization based on the language/culture of the incoming users. You canHereLearn how to localize verification error messages.

Now that we have added the verification feature to the person class, let's re-run our application to see what happens when we type A false value and submit it back to the server:

Note that our application now has a very good error experience. The text element with invalid input is highlighted in red, and the verification error message we specified is also displayed to the user. The form also retains the data that the user originally entered so that they do not need to fill in any more. However, you may ask, why?

To understand this behavior, let's take a look at the create action method for processing the post scenario of our form:

When our HTML form is submitted back to the server, the above method will be called. Because this action method accepts a "person" object as the parameter, ASP. net mvc creates a person object and automatically maps incoming form input values to this object. As part of this process, ASP. net mvc also checks whether the dataannotation verification feature on the person object is valid. If everything is legal, then modelstate in our code. the isvalid check returns the true value. In this case, we (eventually) Save the person object to the database and redirect it back to the home page.

However, if there is any verification error on the person object, our action method will re-display the form with the data of the invalid person object, this is implemented through the last line of code in the code snippet above.

Then, the error message is displayed in our view, because our create form is in every <% = html. textboxfor () %> There Is A <% = html. validationmessagefor () %> auxiliary method call. The HTML. validationmessagefor () auxiliary method outputs an appropriate error message for any invalid model attribute of the incoming View:

One advantage of this mode/method is that it is very easy to configure. It also allows us to easily add or change verification rules on our person class,Without changing any code in the Controller or view. This is the ability to specify verification rules in one place, and then be committed and observed in all places, allowing us to rapidly develop our applications and rules with minimal effort, and keep the code to a very dry level.

Step 3: Enable client Verification

At present, our applications can only perform server-side verification, which means that our end users need to submit the form to the server to see any verification error message.

What's cool about ASP. net mvc 2's validation architecture is that it supports both the server sideAndClient verification. To enable this function, we need to add two JavaScript references to the view and write a line of code:

After these three lines are added, ASP. net mvc 2 will use the verification metadata we add to the person class to connect the client JavaScript verification logic for us. This means that when you use the tab key to jump out of an invalid input element, you will get an instantaneous verification error.

To view examples supported by client Javascript in our friend application, let's re-run the application, enter valid values in the first three text boxes, and then click "CREATE) ". Note: If you do not need to access the server, you will get an instantaneous error message with missing values:

If we enter invalid email characters, the error message will be changed from "email required (email is a required value)" to "not a valid email (email is invalid) "(this is the error message we specified when adding the rule to the person class ):

When a valid email is entered, the error message disappears instantly, and the background color of the text box is restored to normal:

The good thing is that we can enable the above verification logic without writing any custom JavaScript. Our verification code is still so dry. We can specify rules in one place and then execute them in the entire application, both on the client and server.

Note: For security reasons, server-side verification rules are always executed, and you enable client support immediately. This prevents hackers from attempting to bypass client rules and spoof your server.

ASP. net MVC 2 client JavaScript verification support can be used with you in ASP. any verification framework/engine used in the. net mvc application does not require you to use the dataannotation verification method. All infrastructure is independent of dataannotation and can be used with the castle validator, entlib verifies the application block, or you choose to use any custom verification solution.

If you do not want to use our client Javascript file, you can replace it with the jquery verification plug-in and use that library. ASP. net mvc futures download also includes support for enabling jquery verification for ASP. net mvc 2 server-side verification framework.

Step 4: create a custom [email] verification feature

The system. componentmodel. dataannotations namespace in the. NET Framework includes many built-in verification features that you can use. In the preceding example, four of them are used: [required], [stringlength], [range], and [regularexpression].

You can also define your own custom verification features and then apply them. You can inherit from the validationattribute base class in the system. componentmodel. dataannotations namespace to define fully-customized features. Alternatively, you can choose to inherit from any existing verification features, if you only want to extend their basic functions.

For example, to help clear the code in our person class, we may want to create a new [email] verification feature that encapsulates the regular expressions that check valid emails. To do this, we only need to inherit from the regularexpressionattribute base class like this, and then call the constructor of the regularexpressionattribute base class with the appropriate email regular expression:

Then, update the person class to use our new [email] Verification attribute and replace the regular expression we used earlier, which makes our code cleaner and more encapsulated:

When creating custom verification features, you can also specify the verification logic executed on the server side and on the client side through JavaScript.

In addition to creating verification features that can be applied to individual attributes of an object, you can also apply verification features to the class hierarchy, which allows you to implement verification logic for multiple attributes of an object. You can refer to the examples included in the default ASP.. Net MVC 2 accountmodels. CS/vB file "propertiesmustmatchattribute" Custom feature (in vs 2010 file-> new ASP. net MVC 2 web project, and then query the class ).

Step 5: persistence to the database

Now let's implement the logic required to save friend data to the database.

 

At this point, we only use the plain-old C # class (sometimes called the "poco" class, that is, "plain old CLR (or C #) object "). One solution we can use is to write some individual persistent code to map the existing classes that we have compiled to the database. Currently, object relational mapping-ORM (object relational mapping-ORM) solutions such as nhiborm support such poco/PI ing. With.. Net 4 released by ADO. the net Entity Framework (Entity Framework-ef) also supports poco/PI ing, and just like nhib.pdf, EF can also enable the "only Code (Code only)" method (no ing file, you do not need a designer) to define the persistence ing capability.

If our person object is mapped to the database in this way, we do not need to make any changes to the person class or modify any verification rules, and it will continue to work well.

But what if we want to use graphical tools for ORM ing?

Today, many developers who use Visual Studio do not write their own ORM ing/persistent logic, but use the built-in designer in Visual Studio to help manage such ing logic.

A frequently asked question when using dataannotation (or any other form of feature-based verification) is: "If your model object is created/maintained by the GUI designer, how do you apply these features? ". For example, if we use a poco-style person class that is similar to the one we have been using so far, we use a person class in Visual Studio such as LINQ to SQL or ADO. what should we do if a GUI ing tool such as the net EF designer defines/maintains our person class:

The above is a screen that shows a person class defined in vs 2010 using the ADO. Net EF designer. The window above defines the person class, and the window below shows how the attributes of this class are mapped to the people ing editor of the "people" table in the database. When you click Save on the designer, it automatically generates a person class for you in the project. This is great, but every time you make a change and click Save, it willRegenerate the person classThis will lead to the loss of any verification features declared on the object.

One way to apply additional feature-based Metadata (such as verification features) to classes automatically generated/maintained by the vs designer is to use a class called "buddy classes) technology. Basically, you create another class that includes your verification features and metadata, and then apply the "metadatatype" feature to a partial class compiled together with the class generated by the tool, connect it to the class generated by the designer. For example, if we want to apply the verification rules we used earlier to. in the person class maintained by the net EF designer, we can update our verification code so that it is stored in a separate "person_validation" class, use a code like the following to connect it to the "person" class created by:

The above method is not as elegant as the pure poco method, but the advantage is that it can be used for code generated by any tool or designer in Visual Studio.

Last step-Save the friend to the database

In the last step, whether or not poco or the person class generated by the tool is used, legal friend data is stored in the database.

This only requires that we use three lines of code to replace the todo placeholder statement in the friendscontrolle class. These three lines of code save new friends to the database. The following is the complete code of the entire friendscontroller class (using ADO. Net EF for database persistence ):

Now, when we access/Friends/createWe can easily add new users to our friend database during URL:

All data is verified on both the client and server. We can easily add/modify/delete verification rules in one place, and these rules are executed by all controllers and views throughout the application.

Conclusion

ASP. net mvc 2 greatly simplifies web application verification integration. It proposes a model-based verification method that allows you to keep your applications dry and helps ensure that verification rules are consistent throughout the application. The built-in dataannotation support in ASP. net mvc 2 makes it easy to support common verification scenarios. In addition, the scalability support in the ASP. Net MVC 2 verification facility allows you to support a wider range of more advanced verification scenarios and insert any existing or custom verification frameworks/engines.

I hope this article will help you.

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.