.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh

Home >> Forum >> MVC >> Post New QuestionBookmark and Share Subscribe to Forum

Can we use standard .ASP validation controls in MVC web application.

Posted By: Krishna     Posted Date: July 17, 2014    Points:5   Category :MVC
Can we use standard ASP.net Validation controls in MVC web application.
Example Required Validation ect.

Author: ASPEvil             
Posted Date: July 17, 2014     Points: 20   

No, it is not allowed to use those server controls available on ASP.Net, with MVC.

Author: Ashutosh Jha             
Posted Date: July 27, 2014     Points: 20   


I don't think it works. To know about MVC validation go through this-


Ashutosh Jha

Author: Akhil Raj       [Moderator]      
Posted Date: July 29, 2014     Points: 20   

CAn you tell me why this is needed. MVC views can be validated using javascript or in the server side using model validation.

Author: Sambanthamoorthy             
Posted Date: September 02, 2014     Points: 20   

Adding Validation Rules to the Movie Model

You'll begin by adding some validation logic to the Movie class.

Open the Movie.cs file. Notice the System.ComponentModel.DataAnnotations namespace does not contain System.Web. DataAnnotations provides a built-in set of validation attributes that you can apply declaratively to any class or property. (It also contains formatting attributes like DataType that help with formatting and don't provide any validation.)

Now update the Movie class to take advantage of the built-in Required, StringLength, RegularExpression, and Range validation attributes. Replace the Movie class with the following:

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

[StringLength(60, MinimumLength = 3)]
public string Title { get; set; }

[Display(Name = "Release Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

[Range(1, 100)]
public decimal Price { get; set; }

public string Rating { get; set; }
The StringLength attribute sets the maximum length of the string, and it sets this limitation on the database, therefore the database schema will change. Right click on the Movies table in Server explorer and click Open Table Definition:

In the image above, you can see all the string fields are set to NVARCHAR (MAX). We will use migrations to update the schema. Build the solution, and then open the Package Manager Console window and enter the following commands:

add-migration DataAnnotations

When this command finishes, Visual Studio opens the class file that defines the new DbMIgration derived class with the name specified (DataAnnotations), and in the Up method you can see the code that updates the schema constraints:

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));
The Genre field is are no longer nullable (that is, you must enter a value). The Rating field has a maximum length of 5 and Title has a maximum length of 60. The minimum length of 3 on Title and the range on Price did not create schema changes.

Examine the Movie schema:

The string fields show the new length limits and Genre is no longer checked as nullable.

The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input. In the code above, Genre and Rating must use only letters (white space, numbers and special characters are not allowed). The Range attribute constrains a value to within a specified range. The StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length. Value types (such as decimal, int, float, DateTime) are inherently required and don't need the Required attribute.

Code First ensures that the validation rules you specify on a model class are enforced before the application saves changes in the database. For example, the code below will throw a DbEntityValidationException exception when the SaveChanges method is called, because several required Movie property values are missing:

MovieDBContext db = new MovieDBContext();
Movie movie = new Movie();
movie.Title = "Gone with the Wind";
db.SaveChanges(); // <= Will throw server side validation exception
The code above throws the following exception:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Having validation rules automatically enforced by the .NET Framework helps make your application more robust. It also ensures that you can't forget to validate something and inadvertently let bad data into the database.

Validation Error UI in ASP.NET MVC

Run the application and navigate to the /Movies URL.

Click the Create New link to add a new movie. Fill out the form with some invalid values. As soon as jQuery client side validation detects the error, it displays an error message.


Note to support jQuery validation for non-English locales that use a comma (",") for a decimal point, you must include the NuGet globalize as described previously in this tutorial.
Notice how the form has automatically used a red border color to highlight the text boxes that contain invalid data and has emitted an appropriate validation error message next to each one. The errors are enforced both client-side (using JavaScript and jQuery) and server-side (in case a user has JavaScript disabled).

A real benefit is that you didn't need to change a single line of code in the MoviesController class or in the Create.cshtml view in order to enable this validation UI. The controller and views you created earlier in this tutorial automatically picked up the validation rules that you specified by using validation attributes on the properties of the Movie model class. Test validation using the Edit action method, and the same validation is applied.

The form data is not sent to the server until there are no client side validation errors. You can verify this by putting a break point in the HTTP Post method, by using the fiddler tool, or the IE F12 developer tools.

How Validation Occurs in the Create View and Create Action Method

You might wonder how the validation UI was generated without any updates to the code in the controller or views. The next listing shows what the Create methods in the MovieController class look like. They're unchanged from how you created them earlier in this tutorial.

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.
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)
if (ModelState.IsValid)
return RedirectToAction("Index");
return View(movie);
The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version handles the form post. The second Create method (The HttpPost version) calls ModelState.IsValid to check whether the movie has any validation errors. Calling this method evaluates any validation attributes that have been applied to the object. If the object has validation errors, the Create method re-displays the form. If there are no errors, the method saves the new movie in the database. In our movie example, the form is not posted to the server when there are validation errors detected on the client side; the second Create method is never called. If you disable JavaScript in your browser, client validation is disabled and the HTTP POST Create method calls ModelState.IsValid to check whether the movie has any validation errors.

You can set a break point in the HttpPost Create method and verify the method is never called, client side validation will not submit the form data when validation errors are detected. If you disable JavaScript in your browser, then submit the form with errors, the break point will be hit. You still get full validation without JavaScript. The following image shows how to disable JavaScript in Internet Explorer.

Post Reply

You must Sign In To post reply
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend