Server Side Validation In MVC

(ASP.NET MVC)


Hi,

This article is about server side validation in asp.net mvc framework. The VISUAL STUDIO 2012 EXPRESS is used in this article.

To Create the asp.net mvc 4 project, Go to file menu ->select New Project. Once you select the "New Project" menu. The "New Project" dialog appears as shown below

New Project Dialog

In the new project dialog on the left side tree select web node and in the right hand side select "ASP.NET MVC 4 Web Application" Template. In the bottom of the dialog type name of the project then select the project file location and type the solution name, then click ok button. It will open new dialog called "Project Template" as shown below

New Project Template

Select the "Basic" as the project template. Set default the view engine to "razor" then press ok button. It will create the new project to the specified location as shown below.

Project Structure

Right click the controllers folder, select the option "Add Controller" then type the name as HomeController in the Add New Controller dialog as shown below

Add New Controller

Right click the Models folder, Select the Add menu in the context menu then select the "class" in the sub menu as shown below

Add Model

It will bring the "Add New Item" Dialog as shown below

Add Model Dialog 

In the name text box of the AddNewItem Dialog type the model class name as "EmployeeModel" as shown above. Then add the employee properties with the validation attribute as shown below

Employee Model

Create the index action method for the both get and post http verb as shown below.

Home Controller

Right click on the index action method and select the "Add View" option in the context menu, The add view dialog popsup, Check the "Create a strongly-typed view" checkbox. Select the "EmployeeModel" class in Model class dropdown. Select "Create" in the Scaffold template dropdown for scaffolding which creates the index view with the add employee form. Click the add button. The Add view dialog is shown below

Add View

The index view which is created by scaffolding is shown below

Index View

The difference between the client side validation and the server validation is in the server side validation the validation is done on the server side using the ModelState.IsValid property as shown in the HomeController post http verbs action method. We should remove the jqueryvalidation script in the server side validation. 

Once you run the application and click the create the button you will see the following result.

Validation Result


Ratings


Average Rating: 5.00 by 4 users
Giri Prasad
5/24/2015
5/24/2015
Download PDF
Download Project

Comments