ASP. net mvc 5-Add a validator to the Data Model

Source: Internet
Author: User
Tags table definition types of functions

In this section, the validation logic is added to the Movie model. Make sure that these verification rules are executed when you create or edit a movie. One of the core design creden。 of DRYASP. net mvc is DRY: "Do not Repeat Yourself (DRY -- 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 in a place (model class) as declared. This rule will be executed anywhere in the application. Let's see how you can use this verification support in this movie app. To add verification rules for a Movie model, you will first add some verification logic to the Movie class. Open the Movie. cs file and note that the System. Web namespace does not contain System. ComponentModel. DataAnnotations. DataAnnotations, which provides a set of built-in severe attributes for you to apply to classes and attributes. (DataAnnotations also contains a ype attribute to help validate the formatting method.) Update the Movie class to use the built-in Required, StringLength, RegularExpression, and Range verification attributes. The following code is used as an example to describe application verification attributes. Copy the public class Movie {public int ID {get; set;} [StringLength (60, MinimumLength = 3)] public string Title {get; set ;} [Display (Name = "Release Date")] [DataType (DataType. date)] [DisplayFormat (DataFormatString = "{0: yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ReleaseDate {get; set ;} [RegularExpression (@ "^ [A-Z] + [a-zA-z''-'\ s] * $")] [Required] [StringLength (30)] public string Genre {get; set;} [Range (1,100)] [DataType (DataType. currency)] public decimal Price {get; set;} [RegularExpression (@ "^ [A-Z] + [a-zA-z''-'\ s] * $")] [StringLength (5)] public string Rating {get; set ;}} copy the code to set the maximum length of the string in the StringLength attribute. It sets this restriction on the database, therefore, the database schema will change. Right-click the movie Table, in Server explorer, and then click Open Table Definition: clip_image002 in the image above, you can see that all string fields are set to the NVARCHAR (MAX) data type. we will use migration to update the architecture. Generate a solution, open the Package Manager Console, and enter the following command: add-migration DataAnnotations update-database. After the command is complete, visual Studio will open the class code file, which defines the new DbMIgration derived class (DataAnnotations). You can see the update architecture constraint code in the Up method as follows: copy the code public override void Up () {AlterColumn ("dbo. movies "," Title ", c => c. string (maxLength: 60); AlterColumn ("dbo. movies "," Genre ", c => c. string (nullable: false, maxLength: 30); AlterColumn ("dbo. movies "," Rating ", c => c. string (maxLength: 5);} copy the code. The Genre field can no longer be Null (that is, you must enter a value ). The maximum length of the Rating field is 5, and the maximum length of the title is 60. The minimum length of the range of Title and Price is not changed. Check the schema of the movie table in the database: clip_image004. This string field shows the new length limit and Genre field (Genre. The validation attribute specifies the behavior that you want to apply to the model attribute. The Required and MinimumLength attributes indicate that a property cannot be empty, but there is nothing to prevent users from entering spaces for verification. The RegularExpression attribute is used to limit which characters can be entered. In the above Code, Genre and Rating can only use letters (spaces, numbers, and special characters are not allowed ). The value of the Range attribute constraint is within a specified Range. The StringLength attribute allows you to set the maximum length and (optional) of a string attribute ). The value type (decimal, int, float, DateTime) has the Required attribute. Code First make sure that your model is stored in the database before the verification rules are enforced on the specified class. For example, when the following code throws a DbEntityValidationException and calls the SaveChanges method, several necessary Movie attributes are missing: copy the code MovieDBContext db = new MovieDBContext (); movie movie = new Movie (); movie. title = "Gone with the Wind"; db. movies. add (movie); db. saveChanges (); // <= Will throw server side validation exception the code above Will throw the following exception: Validation failed for one or more entities. for more information, see the 'entityvalidationerrors 'attribute. has passed. NET Framework automatically Validation rules are executed to make your application more robust. It also ensures that you do not forget the authentication, that is, you will not inadvertently write bad data into the database. ASP. net mvc verification error UI re-run the application and browse/Movies URL. Click the Create New link to add a New movie. Enter invalid values in the form, and then click the Create button. When an error is detected by jQuery client verification, it displays an error message. Note: To enable jQuery to support the validation of non-English regions using commas, you need to set a comma (",") to indicate the decimal point. As described earlier in this tutorial, you must introduce NuGet globalize. Note that the form has automatically highlighted the text box with a red border color next to each verification error message to indicate invalid data. These errors are enforced on the client side (using JavaScript and jQuery) and server side (if the user disables JavaScript ). One real benefit is that you do not need to change a line of code in the MoviesController class or the Create. cshtml view to enable the user interface for this verification. The Controller and view you created in the previous tutorial are automatically enabled, and the attributes of the Movie model class specified for verification are used. Using the Edit behavior method is also applicable to the same verification method. It will not be sent back to the server until no form data is incorrectly verified by the client. You can verify this by using a breakpoint in the http post method; or by using the fiddler tool, or the IE browser F12 developer tools. You may be curious about how to verify the creation of views and methods. The verification 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 are not modified. Copy the public ActionResult Create () {return View ();} // POST:/Movies/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598 . [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create ([Bind (Include = "ID, Title, ReleaseDate, Genre, Price, Rating")] Movie movie) {if (ModelState. isValid) {db. movies. add (movie); db. saveChanges (); return RedirectToAction ("Index");} return View (movie);} copy the code first (http get) Create method to display the initial form creation. The second ([HttpPost]) method processes form requests. The second Create method (HttpPost version) calls ModelState. IsValid to check whether there are 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 error, the Create 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, the form will not be post to the server. Therefore, the second Create method will never be called. If JavaScript is disabled in the browser, client verification is also disabled. The http post Create method calls ModelState. IsValid to check whether the video contains any verification errors. You can set a breakpoint in the HttpPost Create method. When an error is detected during client verification, no form data will be 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. Clip_image008 clip_image010 shows how to disable JavaScript in Firefox. Clip_image012 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 re-display the view when the verification fails. Copy the code @ model MvcMovie. models. movie @ {ViewBag. title = "Create" ;}< h2> Create

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.