Asp. Net MVC4 Getting Started Guide (8): Add a validator to the Data Model

Source: Internet
Author: User

In this sectionMovieAdd verification logic to the model. Make sure that these verification rules are executed when you create or edit a movie.

Keep things DRY

One of the core design principles of ASP. net mvc is DRY: "Do not Repeat Yourself Don't Repeat Yourself )". ASP. net mvc encourages you to specify a function or behavior, and then apply it to all places of the application. This reduces the amount of code you need to write, reduces code error rates, and facilitates code maintenance.

Providing verification support for ASP. net mvc and Entity Framework Code First is a great practice of the DRY creed. You can specify a verification rule as declared in a local model class. This rule will be executed anywhere in the application.

Let's see how you can use this verification support in this movie app.

Add validation rules for movie Models

You will firstMovieClass to add some verification logic.

OpenMovie. csFile. Add at the top of the fileusingTo referenceSystem.ComponentModel.DataAnnotationsNamespace:

using System.ComponentModel.DataAnnotations;

Note: This namespace does not containSystem.Web. DataAnnotations provides a set of built-in verification features that can be declared and applied to any class or attribute.

UpdateMovieClass to use the built-inRequired,StringLengthAndRangeVerify attributes. The following code is used as an example to describe application verification attributes.

?

Run the application and you will get the following runtime error again:

The model backing the 'moviedbcontext' context has changed since the database was created. Consider using Code First Migrations to update the database (Http://go.microsoft.com/fwlink? LinkId = 238269).

We will use Migrations to update the Schema. Generate a solution, and then openSoftware Package Manager ConsoleWindow, and enter the following command:

add-migration AddDataAnnotationsMig
update-database

After the command is complete, Visual Studio opens the specified nameAddDataAnnotationsMig), Which definesDbMIgrationAndUpMethod, you can see the Schema and constraints of the Code Update.TitleAndGenreThe field can no longer be null, that is, you must enter a value) andRatingThe maximum length of a field is 5.

The verification attribute specifies a verification behavior, so that you can specify the attribute in the model that needs to be forcibly verified. The Required attribute indicates that this attribute must have a value. In this example, a movie must haveTitle,ReleaseDate,GenreAndPriceAttribute Value.RangeAttribute limits a value within a specified range.StringLengthAttribute allows you to set the maximum length and minimum length of a string attribute (optional ). Internal type exampledecimal, int, float, DateTime) Is required by default, so it is not required.RequiredAttribute.

Code First ensures that the verification rules you specify on the model class are executed before the application modifies the database. For example, the following code callsSaveChangesMethod, an exception is thrown because several requiredMovieAttribute value, and the price is zero, which is out of the valid range ).

?

Verification rules are automatically executed by. NET Framework, which helps make your applications more reliable. It also makes sure that you do not forget to verify, and inadvertently write bad data into the database.

The complete code list of the updated Movie. cs file is as follows:

? ASP. net mvc verification error UI

Re-run the application and browse/Movies.

ClickCreate NewLink to add a new movie. Enter invalid values in the form, and then clickCreateButton.

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 564 "height =" 752 "src =" http://www.bkjia.com/uploads/allimg/131228/115F25J5-0.png "/>

Note:To enable jQuery to support the validation of non-English regions using commas, you need to set comma ",") to indicate the decimal point. You need to introduceGlobalize. jsYou also need to specifyCultures/globalize. cultures. jsFile addresses in https://github.com/jquery/globalize) can be used in JavaScriptGlobalize.parseFloat. The following code shows the Views \ Movies \ Edit. cshtml view under "FR-FR" Culture:

?

To use this user authentication interface, the real benefit is that you do not need to modifyMoviesControllerClass orCreate. cshtmlAny line of code in the view. In the controller and view generated before this tutorial,MovieThe validation rules specified on the attributes of the model class can be automatically applied.

You may have noticedTitleAndGenreAttribute. If you enter text in a field or delete text, the required verification properties are not executed until you submit the form (clickCreateButton. For fields that are initially empty, such as fields in the created view) and fields that only have the Required attribute but do not have other verification attributes, you can perform the following operations to trigger Verification:

1. Tab into the field.

2. Enter some text.

3. Tab out.

4. Tab back into the field.

5. Remove the text.

6. Tab out.

The above sequence triggers the required verification, instead of clicking the submit button. If no field is entered, click Submit to trigger client verification. The form data will not be sent to the server until there is no client verification error. You can add a breakpoint to the HTTP Post method on the server, or use Fiddler tool or IE 9 F12 Developer tools.

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 564 "height =" 751 "src =" http://www.bkjia.com/uploads/allimg/131228/115F22H9-1.png "/>

How to verify the view creation and Creation Method

You may be wondering how to generate a verification user interface without updating the Controller or view code. Listed belowMovieControllerClassCreateMethod. They are automatically generated in the previous tutorial and are not modified.

?

First http get)CreateThe method is used to display the initial form creation. Second[HttpPost]) Method to process form requests. SecondCreateMethodHttpPostVersion) callModelState.IsValidTo check for any Movie verification errors. By calling this method, all attributes of the verification constraint applied to the object are verified. If the object contains a verification errorCreateThe method re-displays the initial form. If there are no errors, the method saves the information to the database. In our movie example, we used verification,When the client detects an error,Form will not be post to the server; therefore, the secondCreateMethod will never be called. If you disable JavaScript in your browser, client authentication is also disabled.CreateThe method will call ModelState. IsValid to check whether the video contains any verification errors.

You canHttpPost CreateSet a breakpoint in the method. When an error is detected during client verification, no form data is post, so this method will never be called. If you disable JavaScript in your browser and submit a form with an error message, the breakpoint will hit. You are still fully validated, even if JavaScript is not available. Shows how to disable JavaScript in Internet Explorer.

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 455 "height =" 968 "src =" http://www.bkjia.com/uploads/allimg/131228/115F25528-2.png "/>

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 463 "height =" 223 "src =" http://www.bkjia.com/uploads/allimg/131228/115F24239-3.png "/>

Shows how to disable JavaScript in Firefox.

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 537 "height =" 489 "src =" http://www.bkjia.com/uploads/allimg/131228/115F25B1-4.png "/>

Shows how to disable JavaScript in Chrome.

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 623 "height =" 806 "src =" http://www.bkjia.com/uploads/allimg/131228/115F21063-5.png "/>

The following is the code generated by the framework in the previous tutorial.Create. cshtmlView template. It is used to display the initial form for the above two operation methods, and re-display the view when the verification fails.

?

Please note how to use the codeHtml.EditorForHelper output isMovieFor each attribute in<input>Element. This Helper is nextHtml.ValidationMessageForMethod call. The two Helper methods will process the model object passed to the view by the Controller. here is,MovieObject ). They will automatically search for the verification attribute specified in the model and display the appropriate error message.

If you want to change the verification logic later, you can add the verification information to the Model in one place. In this example, yesmovieClass ). You don't have to worry about noncompliance. The verification logic is executed in different parts of the application-defining the verification logic in one place will be used everywhere. This makes the code very clean and easy to maintain and expand. It means that you will fully abide by the DRY principle.

Add Formatting to the video model

OpenMovie. csFile and viewMovieClass.System.ComponentModel.DataAnnotationsThe namespace provides the format attributes of the Built-in validation feature set. We have applied the release date and price fields.DataTypeEnumeration value. The following code is used as an example.ReleaseDateAndPriceAttributes and correspondingDisplayFormatAttribute.

?

DataTypeAttributes are not verification features, they are used to tell the view engine how to Render HTML. In the preceding example,DataType.DateProperty to display the video date as a date, for example, the followingDataTypeThe attribute does not verify the data format:

[DataType(DataType.EmailAddress)]
[DataType(DataType.PhoneNumber)]
[DataType(DataType.Url)]

The properties listed above only provide the view engine to display data in the format of <a> URL and

Another useDataTypeAttribute method, you can explicitly setDataFormatString. The following code demonstrates the Release Date attribute with a Date Format String, that is, "d ").

       [DisplayFormat(DataFormatString = "{0:d}")]
       public DateTime ReleaseDate { get; set; }

The following code setsPriceThe property is in the currency format.

       [DisplayFormat(DataFormatString = "{0:c}")]
       public decimal Price { get; set; }

CompleteMovieClass is as follows.

?

Run the application and browseMoviesController. The release date and price are well formatted. Displays the Release Date and the Price using the "FR-FR" Culture.

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 679 "height =" 672 "src =" http://www.bkjia.com/uploads/allimg/131228/115F23540-6.png "/>

Is the English US of the default Culture ).

650) this. width = 650; "style =" border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-right -: "title =" image "border =" 0 "alt =" image "width =" 676 "height =" 665 "src =" http://www.bkjia.com/uploads/allimg/131228/115F23a3-7.png "/>

In the next section, we will first look at the code and then improve the automatically generatedDetailsAndDeleteMethod.



Bytes --------------------------------------------------------------------------------------------------------------------

Note:

This series contains nine articles translated from Asp. net MVC4 official tutorial, due to the concise description of this series of articles, the length is moderate, from an example to explain, the full text finally completed a small system for managing movies, very suitable for beginners Asp.. Net MVC4. Nine articles:

1. Introduction to Asp. Net MVC4

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

· Address: http://www.cnblogs.com/powertoolsteam/archive/2012/11/01/2749906.html

2. Add a controller

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

· Address: http://www.cnblogs.com/powertoolsteam/archive/2012/11/02/2751015.html

3. Add a view

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view

· Address: http://www.cnblogs.com/powertoolsteam/archive/2012/11/06/2756711.html

4. Add a model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model

· Address: http://www.cnblogs.com/powertoolsteam/archive/2012/12/17/2821495.html

5. Access the data model from the Controller

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller

· Address: http://www.cnblogs.com/powertoolsteam/archive/2013/01/11/2855935.html

6. Verify the editing method and view

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view

· Address: http://www.cnblogs.com/powertoolsteam/archive/2013/01/24/2874622.html

7. Add new fields to the movie table and Model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table

· Address: http://powertoolsteam.blog.51cto.com/2369428/1140334

8. Add a validator to the Data Model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

· Address: http://powertoolsteam.blog.51cto.com/2369428/1147449

9. query details and delete records

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-details-and-delete-methods

· Address: http://powertoolsteam.blog.51cto.com/2369428/1149311

10. Third-party control Studio for ASP. NET Wijmo MVC4 tool Application

Address: http://powertoolsteam.blog.51cto.com/2369428/1196469









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.