Learn ASP. NET MVC5 Official Tutorial Summary (10) Add validation

Source: Internet
Author: User

Learn ASP. NET MVC5 Official Tutorial Summary (10) Add validation

in this chapter, we will add validation logic for the movie model and confirm that validation rules are valid when users try to create and edit movies using a program.

   ASP.NET MVC  A core principle of dry ( don "T REPEAT YOURSELF -  do not repeat things). ASP.NET MVC  encourage you to specify functions or behaviors at once, and then map them to other parts of the application, which reduces the amount of code, reduces the likelihood of errors, and is easier to maintain.

The validation capabilities provided by the ASP. NET MVC and Entity Framework Code First are good practices for the DRY principle. You can define validation rules in one place (in a model class) so that you can use this rule everywhere in your application.

Let's take a look at how to Add advanced validation rules to the current Movie.

Now let's start adding some validation rules to the Movie class.

Open file Movie.cs, note that namespace System.ComponentModel.DataAnnotations does not contain system.web . dataannotations provides built-in validation features that you can use in any class or property (it also contains formatting features like DataType, They do not participate in any validation).

Add some built-in validation rules for the Movie class, and the modified code is as follows:

public class movie{Public    int ID {get; set;}    [Required]    [Stringlength (minimumlength = 3)]    public string Title {get; set;}    [Display (Name = "Release Date")]    [DataType (datatype.date)]    Public DateTime releasedate {get; set;}    [Required]    public string Genre {get; set;}    [Range (1, +)]    [DataType (datatype.currency)]    Public decimal price {get; set;}    [Stringlength (5)]    [Required]    public string Rating {get; set;}}

Use data migration to update the database structure. Compile the solution, and then open the Package Manager console window and execute the following command:

Add-migration Dataannotationsupdate-database

After the execution of these two commands,Visual Studio created the dataannotations class for us, which inherits from the dbmigration . Open the file, in its up method, you will see the code to upgrade the structure:

public override void Up () {Altercolumn ("dbo.    Movies "," Title ", C = c.string (Nullable:false, maxlength:60)); Altercolumn ("dbo.    Movies "," Genre ", C = c.string (Nullable:false)); Altercolumn ("dbo. Movies "," Rating ", C = c.string (Nullable:false, Maxlength:5));} 

As you can see from the code, theTitle,Genre , and Rating Three fields are no longer allowed to be empty (which means you must enter a value). The maximum length of the Rating field is 5, and the maximum length of the Title is The minimum length is 3.

Code First ensures that the data is validated with the rules you specify when it is saved to the database, for example, the following code throws an error when calling SaveChanges:

Moviedbcontext db = new Moviedbcontext (); Movie movie = new Movie (), movie. Title = "Gone with the Wind";d B. Movies.add (movie);  Db. SaveChanges (); <= throws a server segment error because the required fields in movie are not assigned

Validation rules automatically take effect when saved to make the program more robust, it can be in you forget to verify, and inadvertently prevent illegal access to the database.

Run the application, browse the address /movies, and click on the "Create New" link to add a movie. If we have some illegal data in the input process, the client will display some errors, which are implemented by jQuery client authentication.

When an error occurs, the text box is added with a red border and a description of the error message is displayed. These error messages can take effect on the client (using JavaScript and jQuery) and the server (when client Javascript is invalid).

A real benefit is that you don't need to modify one line of code in moviescontroller or create.cshtml to enable client-side validation, and the controller and view will be based on what we previously defined in The validation attribute in the Movie class automatically selects the validation rule.

The form data is not submitted to the server side when there is an error.

You might find it strange that client-side validation is generated without modifying the controller or view code. The following code shows the Create method for Moviecontroller , which, like the create code in the previous tutorial , has not been modified:

GET:/movies/createpublic actionresult Create () {    return View ();} POST:/movies/create[httppost][validateantiforgerytoken]public actionresult Create (movie movie) {    if ( Modelstate.isvalid)    {        db. Movies.add (movie);        Db. SaveChanges ();        Return redirecttoaction ("Index");    }    return View (movie);}

First oneCreatemethod displays one form, and the secondCreatemethod to handlePOSTrequest the submitted form data. A secondCreateMethod InvocationModelstate.isvalidto checkmovieIf there is a validation error in the data, call this method to check the validation rule, if there is an error,Createmethod will re-display the form, and if not, it willMoviedata is saved to the database. In our example, the form is not submitted to the server when the validation error occurs, and the secondCreatemethod will not be called. If you disable theJavascriptClient authentication, secondCreatemethod invokes theModelstate.isvalidCheck the data.

You can monitor whether it is called by adding breakpoints in the httppost Create method. When the client has an error, the form will not be submitted, and if we disable the client's Javascript, the form will submit the wrong data to the server, and the breakpoint will be traced.

The following is the code for the  CREATE.CSHTML&NBSP; view, It is used by the controller create method to display the initial Span style= "Font-family:verdana" >form or re-displays form data with error messages when an error occurs.

@model mvcmovie.models.movie@{viewbag.title = "Create";} 

Open file movie.cs , check movie system.componentmodel.dataannotations  RELEASEDATE&NBSP; Span style= "Font-family:verdana" >price field used datatype enumeration, the following code shows the releasedate price used in the property displayformat features:

[Display (Name = "Release Date")] [DataType (datatype.date)]public DateTime releasedate {get; set;} [Range (1, 100)] [DataType (datatype.currency)]public decimal price {get; set;}

The DataType feature is not a validation feature, they are used to tell the engine how to draw HTML. In the example above,thedatatype.date feature causes the releasedate to display only the date part, not the time. The following DataType attribute does not verify the format of the data:

[DataType (Datatype.emailaddress)] [DataType (Datatype.phonenumber)] [DataType (Datatype.url)]

These features provide recommendations only when trying to format the engine to display data. You can use the regularexpression feature to verify the format of the data.

In addition to using the off-the-shelf DataType formatting features, you can also specify dataformatstring values explicitly. The following code shows the ReleaseDate property uses a formatted string, which you can use to not display The time portion of the ReleaseDate date:

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

The following code displays the price as a currency format:

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

The complete Movie Class code is as follows:

public class movie{Public    int ID {get; set;}    [Required]    [Stringlength (minimumlength = 3)]    public string Title {get; set;}    [Display (Name = "Release Date")]    [DataType (datatype.date)]    Public DateTime releasedate {get; set;}    [Required]    public string Genre {get; set;}    [Range (1, +)]    [DataType (datatype.currency)]    Public decimal price {get; set;}    [Stringlength (5)]    [Required]    public string Rating {get; set;}}

The following code shows how to combine attributes on a single line:

public class movie{Public    int ID {get; set;}    [Required, Stringlength (minimumlength = 3)]    public string Title {get; set;}    [Display (Name = "Release Date"), DataType (datatype.date)]    Public DateTime releasedate {get; set;}    [Required]    public string Genre {get; set;}    [Range (1, +), DataType (datatype.currency)]    Public decimal price {get; set;}    [Required, Stringlength (5)]    public string Rating {get; set;}}

In the next chapter, we'll review the entire application and make some improvements to the automatically generated Details and Delete methods.











Learning ASP. NET MVC5 Official Tutorial Summary (10) Add validation

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.