MVC Model Validation

Source: Internet
Author: User
Tags http post

The ASP. NET MVC Framework provides the API for data validation, called model data annotations or model metadata, which allows us to specify the rules of validation in the model using declarative syntax, the common validation APIs are as follows:

Validation API
Data Validation API Example Description
Compare [Compare ("Myotherproperty")] Two attribute values must be the same
Range [Range (10,20)] The property value must be within the specified data range
RegularExpression [RegularExpression ("Patttern")] Property values must match regular expressions
Required [Required] Property value must be non-empty or not just a space
Stringlength [Stringlength (10)] Property value length cannot exceed the given maximum length

The data validation API is located in the using System.ComponentModel.DataAnnotationsnamespace.

Movie.cs

    usingSystem.ComponentModel.DataAnnotations; //Reference Namespaces//film Information class     Public classMovie {//Movie Name[Display (Name ="Movie Name")] [Required (ErrorMessage="' {0} ' must be filled in")]         Public stringTitle {Get;Set; } //Release Time[Display (Name ="Release Time")] [Required (ErrorMessage="' {0} ' must be filled in")] [DataType (datatype.date)] PublicDateTime ReleaseDate {Get;Set; } //CD Price[Display (Name ="CD Price")] [Required (ErrorMessage="' {0} ' must be filled in")] [Range (typeof(decimal),"1"," -", errormessage ="' {0} ' is not within 1-100")]        //[DataType (datatype.currency)]         Public decimalPrice {Get;Set; } //Ratings[Display (Name ="Ratings")]        //[Required (errormessage = "" {0} "must be filled in")]//[Stringlength (errormessage = "{0}" cannot be longer than ten ")][RegularExpression (@"^[0-9]*[1-9][0-9]*$", errormessage ="' {0} ' cannot be longer than 2")]         Public stringRating {Get;Set; } }

Index.cshtml

<body> @using (Html.BeginForm ()) {<p> movie Name: @Html. TextBox ("Title") </p> <p> release time: @Html. TextBox ("ReleaseDate") </p> <p> disc Price: @Html. TextBox (" Price") </p> <p> Movie Rating: @Html. TextBox ("Rating") </p> <input type="Submit"Id="Submit"Value="Submit"/>@Html. ValidationSummary ()<p> @ViewBag .info</p>    }</body>

HomeController.cs

 Public classHomecontroller:controller {//Get access/home/index         PublicActionResult Index () {returnView (); }        //Model Binding//Post Access/home/index[HttpPost] Publicactionresult Index (Movie m) {if(modelstate.isvalid) {Viewbag.info="movie"+ M.title +", Release time"+ M.releasedate +", Rating"+ m.rating +", the price"+M.price; }            returnView (); }    }

Run:

    

Explain:

In the Model object movie class, the validation behavior for each property is set by using the data annotation method.

In the view, we use the HTML helper method to create the form. At the same time, the Html.validationsummary method can display the validation prompt on the page again.

In HomeController, two versions of the index action method are created, the parameterless index is used to display the page, and index with the parameter is responsible for processing the POST request. The Modelstate.isvalid property checks the validation rules for each property of the model object, and if the validation passes, Modelstate.isvalid returns True, otherwise false is returned.

Remind:

If you need to implement JavaScript client validation, we can use jquery validate to validate the plug-in. We know that if the view implements client-side validation, once the input error is detected, the page is not committed and the form is not sent to the server, the HTTP post version of the index method will not be called. However, client authentication is not a substitute for server-side validation, and if the browser disables JavaScript or a network attack, client-side validation will be completely out of the way, and the server model cannot be validated or missing, and the Modelstate.isvalid method will assume the responsibility of the review and decide whether to validate it.

    

MVC Model 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.