asp.net MVC4 tutorial (eight): adding validators to the data model _ self-study process

Source: Internet
Author: User
Tags extend http post

In this section, you will add validation logic to the movie model. And make sure that these validation rules are executed when a user creates or edits a movie.

Keep things DRY

One of the core design tenets of asp.net MVC is dry: "Don't repeat yourself (Don t Repeat yourself)." asp.net MVC encourages you to specify functionality or behavior, do it once, and then apply it to different parts of your application. This reduces the amount of code you need to write and reduces code error rates, which are easy to code maintain.

Providing validation support for ASP.net MVC and Entity Framework Code First is a great practice of the DRY creed. You can specify validation rules in one place (the model class) declaratively, and this rule is executed anywhere in the application.

Let's see how you can use this validation support in this movie application.

Add validation rules to a movie model

You will first add some validation logic to the movie class.

Open the Movie.cs file. Add a using statement to the top of the file to reference the System.ComponentModel.DataAnnotations namespace:

Using System.ComponentModel.DataAnnotations;

Note that the namespace does not contain system.web. DataAnnotations provides a set of built-in validation features that you can apply to any class or attribute in a declarative manner.

Update the movie class to take advantage of the built-in required, stringlength, and range validation properties. Use the following code as an example to apply a validation property.

public class Movie {public
  int ID {get; set;}

  [Required]
  public string Title {get; set;}

  [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)]
  public string Rating {get; set;}
}

Running the application, you will get the following run-time error again:

The model backing the ' moviedbcontext ' context has changed since the database is created. Consider using Code migrations to update the database (http://go.microsoft.com/fwlink/? linkid=238269).

We will use migrations to update the Schema. Build the solution, and then open the Package Manager Console window and enter the following command:

Add-migration Adddataannotationsmig
Update-database

When this command is finished, Visual studio opens the file with the specified name (adddataannotationsmig), which defines a new class derived from Dbmigration, and in the up method, you can see the schema of the Code update and constraint conditions. The Title and genre fields can no longer be null (that is, you must enter a value) and the Rating field has a maximum length of 5.

The validation property specifies a validation behavior so that you can specify that the attribute in the model needs to be forced to validate. The Required property indicates that the property must have a value, in this example, that a movie must have the value of the title, ReleaseDate, genre, and price attributes to be valid. The Range property restricts a value within a specified range. The Stringlength property allows you to set the maximum length and the minimum length of a string property (optional). Internal types (such as decimal, int, float, DateTime) are required by default, so the required property is not required.

Code first ensures that the validation rules that you specify on the model class are executed before the application modifies the database. For example, the following code throws an exception when it calls the SaveChanges method because a few required movie property values are missing and the price is 0 (this is outside the valid range).

Moviedbcontext db = new Moviedbcontext ();

Movie Movie = new Movie ();
Movie. Title = "Gone with the Wind";
Movie. Price = 0.0M;

Db. Movies.add (movie); 
Db. SaveChanges ();    

Validation rules are automatically executed by the. NET framework, which helps make your application more reliable. It also ensures that you don't accidentally make bad data written to the database because you forgot to verify it.

The following is a complete code listing of the updated Movie.cs file:

Using System;
Using System.Data.Entity;
Using System.ComponentModel.DataAnnotations;

namespace Mvcmovie.models {public
  class Movie {public
    int ID {get; set;}

    [Required]
    public string Title {get; set;}

    [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)]
    public string Rating {get; set;}
  }

  public class Moviedbcontext:dbcontext {public
    dbset<movie> Movies {get; set;}}}

Validation error UI for ASP.net MVC

Rerun the application and browse the /movies URL.

Click the Create new link to add a new movie. Fill in the form with some invalid values, and then click the Create button.

Note , in order for jquery to support non-English domain validation using commas, you need to set the comma (",") to represent the decimal point, you need to introduce globalize.js and you need to specify the specific Cultures/globalize.cultures.js files (addresses in https://github.com/jquery/globalize) can be used in JavaScript Globalize.parsefloat. The following code shows the views\movies\edit.cshtml view under "FR-FR" Culture:

 @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script src= "~/script S/globalize.js "></script> <script src=" ~/scripts/globalize.culture.fr-fr.js "></script> <
        Script> $.validator.methods.number = function (value, Element) {return this.optional (element) | |
    !isnan (Globalize.parsefloat (value));
    } $ (document). Ready (function () {globalize.culture (' fr-fr ');
  }); </script> <script> jquery.extend (jQuery.validator.methods, {range:function) (value, Element, PA
        RAM) {//use The globalization plugin to parse the value var val = $.global.parsefloat (value); return this.optional (Element) | |
      (Val >= param[0] && val <= param[1]);

  }
    }); </script>} 

In order to use this user authentication interface, the real benefit is that you do not need to modify any line of code in the Moviescontroller class or create.cshtml view. In the controller and view generated prior to this tutorial, the validation rules specified on the properties of the movie model class are automatically applicable.

You may have noticed the title and genre properties, and entering text or deleting text in a field will not perform the required validation properties until you submit the form (the dot Create button). For fields that are initially empty (such as creating a field in a view) and a field that has no other validation property than the Required property, you can trigger the validation by doing the following:

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 order above will trigger the required validation, without having to click the Submit button. By clicking the Submit button without entering any fields, client validation is triggered. form data is sent to the server until there is no client validation error. You can test it by adding a breakpoint to the server-side HTTP Post method, or using Fiddler tool or IE 9 F12 Developer tools.

How to validate creating views and creating methods

You may be wondering how the validation user interface is generated without updating the controller or view code. The Create method in the Moviecontroller class is listed below. They are automatically generated in the previous tutorial and have not been modified.


//Get:/movies/create public

actionresult Create ()
{return
  View ();
}
//POST:/movies/create

[httppost] public
actionresult Create (Movie Movie)
{
  if ( Modelstate.isvalid)
  {
    db. Movies.add (movie);
    Db. SaveChanges ();
    Return redirecttoaction ("Index");
  }

  return View (movie);
}

The first (HTTP get) Create method is used to display the initial creation form. The second ([HttpPost]) method handles the request for the form. The second Create method (HttpPost version) calls Modelstate.isvalid to check for any movie validation errors. Calling this method validates all properties on the object that have the validation constraint applied to it. If the object contains validation errors, the Create method will display the original form again. If there are no errors, the method saves the information to the database. In our movie example, we used validation, and when the client detects an error, theform is not posted to the server, so the second Create method is never invoked . If you disable JavaScript in the browser, client authentication is also disabled, and the HTTP POST create method calls Modelstate.isvalid to check whether the movie contains any validation errors.

You can set a breakpoint in the HttpPost create method that does not post form data when the client verifies that an error is detected, so the method is never called. If you disable JavaScript in the browser and then submit a form with an error message, the breakpoint will be hit. You are still fully validated, even in the absence of JavaScript. The following illustration shows how to disable JavaScript in Internet Explorer.

The following figure shows how to disable JavaScript in the Firefox browser.

The following figure shows how to disable JavaScript in the Chrome browser.

The following is the create.cshtml view template generated by the framework code in the previous tutorial. It is used to display the initial form for the above two actions, and to display the view again when a validation error occurs.

Notice how the code uses the Html.editorfor helper to output the <input> element for each property in movie. Next to this helper is a call to the Html.validationmessagefor method. These two helper methods handle the model objects passed by the controller to the view (here is the movie object). They automatically find the validation properties specified in the model and display the appropriate error message.

If you want to change the validation logic later, you can do it in one place and add the validation information to the model. (In this example, the movie Class). You don't have to worry about not conforming to the rules, the validation logic will be executed in different parts of the application--defining validation logic in one place will be used everywhere. This makes the code very clean and makes it easy to maintain and extend. It means that you will fully comply with the dry principle.

Add formatting to the movie model

Open the Movie.cs file and view the Movie class. The System.ComponentModel.DataAnnotations namespace provides a built-in format attribute for the set of validation attributes. We have applied the DataType enumeration value for the release date and Price fields. The following code examples the ReleaseDate and price properties and the corresponding DisplayFormat properties.

[DataType (Datatype.date)] public DateTime releasedate {get; set;} [DataType (datatype.currency)] public decimal price {get; set;}

The DataType property is not a validation attribute and is used to tell the view engine how to render HTML. In the previous example, the Datatype.date property displays the movie date as a date, for example, the following DataType property does not validate the format of the data:

Copy Code code as follows:
[DataType (Datatype.emailaddress)]
[DataType (Datatype.phonenumber)]
[DataType (Datatype.url)]

The properties listed above provide only the view engine to display data in a format such as:<a> as URL,< href= "mailto:EmailAddress.com" > for e-mail. You can use regular expression properties to verify the format of the data. )

Another way to use the DataType property is to explicitly set the dataformatstring. The following code examples the release date property (that is, "D") with a date format string.

Copy Code code as follows:
[DisplayFormat (dataformatstring = "{0:d}")]
Public DateTime releasedate {get; set;}

The following code sets the price property to currency format.

Copy Code code as follows:
[DisplayFormat (dataformatstring = "{0:c}")]
Public decimal price {get; set;}

The complete movie class is shown below.

@model MvcMovie.Models.Movie @{viewbag.title = "Create";}
 

Run the application and browse to the movies controller. A good format for the release date and price. The following figure shows the release date and price using the "Fr-fr" Culture.

The following illustration shows the default culture (中文版 US).

In the next section, we'll look at the code and then refine the automatically generated details and Delete methods.

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.