In this section, you will Movie
add validation logic to the model. And make sure that these validation rules are executed when the user creates or edits a movie.
Keep things DRY
One of the core design tenets of ASP. 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 all parts of your application. This reduces the amount of code you need to write, and reduces the rate of code errors, making it easy to maintain code.
Providing validation support for ASP. NET MVC and Entity Framework Code First is a great practice for the DRY creed. You can specify validation rules declaratively in one place (model Class), which executes 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 Movie
add some validation logic to the class.
Open the Movie.cs file. Add a statement at the top of the file using
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 declaratively to any class or property.
Updates the Movie
class to take advantage of built-in Required
, StringLength
and Range
validation properties. Take the following code as an example to apply the validation attribute.
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;}}
Run the application and you will get the following run-time 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. 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 a file with the specified name (adddataannotationsmig), which defines the new class that is derived from, DbMIgration
and in the Up
method, you can see the schema of the Code update and constraint conditions. Title
and Genre
fields can no longer be null (that is, you must enter a value) and Rating
the field has a maximum length of 5.
The validation property specifies a validation behavior so that you can specify that the property in the model needs to be forced to validate. The Required property indicates that the property must have a value, in this example, a movie must have a Title
ReleaseDate
value of,,, and a property in order to be Genre
Price
valid. Range
property restricts a value within a specified range. StringLength
The default property allows you to set the maximum length of a string property and its minimum length (optional). The intrinsic type (for example decimal, int, float, DateTime
) is required by default, so no attributes are required 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 the method is called, SaveChanges
because several 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 (); <= would throw server side validation exception
Validation rules are automatically executed by the. NET framework, which will help make your application more reliable. It also makes sure that you don't accidentally write bad data 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.
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 that in order for jquery to support validation of non-English regions using commas, you need to set a 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 the "FR-FR" culture:
@section Scripts { @Scripts. Render ("~/bundles/jqueryval") <script src= "~/scripts/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, param) { //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 MoviesController
any line of code in the class or create.cshtml view. In the controller and view generated earlier in this tutorial, the Movie
validation rules specified on the properties of the model class are automatically applied.
You may have noticed the Title
and Genre
attributes, entered text in a field, or deleted text, and will not perform the required validation properties until you submit the form (the point Create button). For fields that are initially empty (such as creating a field in a view) and have only the required property and no other validation properties, you can do the following to trigger validation:
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 the need to click the Submit button. If you do not enter any fields, clicking the submit button directly triggers client authentication. The form data is not sent to the server until there is no client validation error. You can test by adding breakpoints to the server-side HTTP Post method, or using Fiddler tool or IE 9 F12 Developer tools.
How to verify creating views and creating methods
You may be wondering how the validation user interface was generated without updating the controller or view code. The MovieController
methods in the class are listed below Create
. They are automatically generated in the previous tutorials and are not modified.
GET:/movies/createpublic 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 create form. The second ( [HttpPost]
) method processes the request for a form. The second Create
method ( HttpPost
version) ModelState.IsValid
is called to check if there are any movie validation errors. Calling this method validates all properties on the object that have validation constraints applied to them. If the object contains validation errors, the Create
method will re-display the original form. If there are no errors, the method saves the information to the database. In our movie example, we used the validation that theform would not be post to the server when the client detected an error,so the second Create method would never be called . If you disable JavaScript in your browser, client-side validation is also disabled, and the HTTP POST Create
method calls Modelstate.isvalid to check if the movie contains any validation errors.
You can HttpPost Create
set a breakpoint in a method that does not post the form data when the client verifies that an error is detected, so the method is never called. If you disable JavaScript in your 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. Shows how to disable JavaScript in Internet Explorer.
Shows how to disable JavaScript in Firefox.
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 operation methods, and to re-display the view in case of an error in validation.
Notice how the code uses the Html.EditorFor
helper output as an Movie
element in each of the properties <input>
. Next to this helper is a call to the Html.ValidationMessageFor
method. These two helper methods will handle the model objects passed to the view by the controller (in this case, 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). Instead of worrying about noncompliant rules, validation logic executes in different parts of the application-defining validation logic in one place that will be used everywhere. This makes the code very clean and makes it easy to maintain and extend. It means that you will comply fully with the dry principle.
Add formatting to a movie model
Open the Movie.cs file and view the Movie
class. The System.ComponentModel.DataAnnotations
namespace provides a built-in format property for the validation attribute set. We have applied the enumeration values for the release date and Price fields DataType
. The following code example has the ReleaseDate
and Price
properties associated with the property DisplayFormat
.
[DataType (Datatype.date)] public DateTime releasedate {get; set;} [DataType (datatype.currency)] public decimal price {get; set;}
DataType
Properties are not validation attributes, and they are used to tell the view engine how to render HTML. In the example above, 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:
[DataType (Datatype.emailaddress)]
[DataType (Datatype.phonenumber)]
[DataType (Datatype.url)]
The properties listed above provide only the view engine to display the format of the data (such as:<a> for URL,< href= "mailto:EmailAddress.com" > For e-mail. You can use the regular expression property to verify the format of the data. )
Another DataType
way to use properties is to set them explicitly DataFormatString
. The following code example sets the release date property (that is, "D") with a date format string.
[DisplayFormat (dataformatstring = "{0:d}")]
Public DateTime releasedate {get; set;}
The following code sets the Price
property to currency format.
[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. Good formatting of the release date and price. Displays the release date and the price of Culture using "FR-FR".
The display for the default culture (English US).
In the next section, we'll look at the code first and then improve the auto-generated Details
and Delete
methods.
ASP. MVC4 Getting Started Guide (8): Adding a validator to a data model