Learn ASP. NET MVC5 official tutorial Summary (10) add verification,. netmvc5

Source: Internet
Author: User

Learn ASP. NET MVC5 official tutorial Summary (10) add verification,. netmvc5
Learn ASP. NET MVC5 official tutorial Summary (10) add Verification

In this chapter, we will add verification logic for the Movie model and confirm that verification rules are valid when users attempt to create and edit movies using programs.

A core principle of ASP. net mvc is DRY (Don't Repeat Yourself-do not Repeat things ). ASP. net mvc encourages you to specify a function or behavior at a time, and then get it from other aspects of the application through ing. This reduces a lot of code and reduces the possibility of errors, it is easier to maintain.

The validation function provided by ASP. net mvc and Entity Framework Code First is a good practice of the DRY principle. You can define verification rules in one place (in the model class) so that they can be used in all places in the application.

Next, let's take a look at how to add advanced verification rules in the current Movie.

Now we start to add some validation rules for the Movie class.

Open the file Movie. cs. Note that the namespace System. ComponentModel. DataAnnotations does not include System. Web. DataAnnotations provides built-in verification features that you can use in any class or attribute (it also contains formatting features such as DataType that do not participate in any verification ).

Add some built-in verification rules for the Movie class. The modified code is as follows:

public class Movie{    public int ID { get; set; }    [Required]    [StringLength(60, 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, 100)]    [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, open the "Package Manager Console" window, and execute the following command:

add-migration DataAnnotationsupdate-database

After these two commands are executed, Visual Studio creates the DataAnnotations class for us, which inherits from DbMigration. Open the file. In its Up method, you will see the code for upgrading 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));}

From the code, we can see that the Title, Genre, and Rating fields are no longer allowed to be blank (this means you must enter a value ). The maximum length of the Rating field is 5, the maximum length of the Title is 60, and the minimum length is 3.

Code First ensures that the data is verified using the rules you specify when saving the data 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"; db. movies. add (movie); db. saveChanges (); // <= will cause a server segment error, because the required fields of movie are not assigned a value.

The verification rules take effect automatically when they are saved, making the program more robust. It can prevent illegal access to the database when you forget to verify them.

Run the application, browse the address/movies, and click "Create New" to add a movie. If some illegal data occurs during the input process, the client will display some errors, which are achieved through jQuery client verification.

When an error occurs, a red border is added to the text box and an error description is displayed. These error messages can take effect in the client (using Javascript and jQuery) and server (when the client Javascript is invalid) segments.

One real benefit is that you do not need to go to MoviesController or Create. modify a line of code in cshtml to enable client verification. The controller and view automatically select verification rules based on the verification features we previously defined in the Movie class.

When the form data is incorrect, It is not submitted to the server.

You may wonder how client-side verification is generated without modifying the Controller or view code. The following code shows the Create method of MovieController. It is the same as the Create code in the previous tutorial and 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);}

The first Create method displays a form, and the second Create method is used to process the form data submitted by the POST request. The second Create method calls ModelState. isValid to check whether the movie data has a verification error. Call this method to check the verification rule. If there is an error, the Create method will re-display this form. If not, the Movie data is saved to the database. In our example, when an error occurs during verification, the form is not submitted to the server, and the second Create method is not called. If you disable Javascript client verification, the second Create method will call ModelState. IsValid to check the data.

You can add a breakpoint to the HttpPost Create method to check whether a breakpoint is called. When an error occurs on the client side, the form will not be submitted. If we disable Javascript on the client side, the form will submit the error data to the server, and the breakpoint will be tracked.

The following is the code of the Create. cshtml view. It is used by the Create method in the Controller to display the initial form, or re-display the form data with error information when an error occurs.

@model MvcMovie.Models.Movie@{   ViewBag.Title = "Create";}

Open the file Movie. cs and check the Movie class. In addition to a set of built-in verification features, the System. ComponentModel. DataAnnotations namespace also provides the formatting feature. The DataType enumeration has been used in the ReleaseDate and Price fields. The following code shows the DisplayFormat features used in the ReleaseDate and Price attributes:

[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. It is used to tell the engine how to plot HTML. In the preceding example, the releype. Date feature enables ReleaseDate to display only the Date part, but not the time. The following DataType feature does not verify the data format:

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

These features are only recommended when you try to format and display data in the engine. You can use the RegularExpression feature to verify the data format.

In addition to the existing ype formatting feature, you can also specify the DataFormatString value. The following code shows how to format a string using the ReleaseDate attribute. You can use it to not display the time part of the ReleaseDate Date:

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

The following code shows the Price as the 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(60, 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, 100)]    [DataType(DataType.Currency)]    public decimal Price { get; set; }    [StringLength(5)]    [Required]    public string Rating { get; set; }}

The following code combines features into one row for display:

public class Movie{    public int ID { get; set; }    [Required, StringLength(60, 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, 100), DataType(DataType.Currency)]    public decimal Price { get; set; }    [Required, StringLength(5)]    public string Rating { get; set; }}

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











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.