How to validate data provided in MVC URL’s (MVC Tutorial number 8)?

Questpond
Posted by in ASP.NET MVC category on for Advance level | Points: 250 | Views : 23925 red flag

This is the 8th MVC (Model view controller) tutorial and in this article we try to understand how we can validate data passed in MVC URL’s. In case you are completely new to MVC (Model view controller), do have a look at the previous articles and videos given in the table below for quick start.

How to validate data provided in MVC URL’s (MVC Tutorial number 8)?
 

Introduction

This is the 8th MVC (Model view controller) tutorial and in this article we try to understand how we can validate data passed in MVC URL’s. In case you are completely new to MVC (Model view controller), do have a look at the previous articles and videos given in the table below for quick start.
 

Article description

MVC ( Model view controller) videos

MVC ( Model view controller) Article links

A simple Hello world ASP.NET MVC ( Model view controller) application.

Hello word MVC Tutorial video

http://www.dotnetfunda.com/articles/article1297-how-to-create-a-simple-hello-world-aspnet-mvc-tutorial-no-1-.aspx 

In this video we will see how we can share data between controller and the view using view data.

MVC Tutorial video 2 Viewdata

http://www.dotnetfunda.com/articles/article1310-how-to-pass-data-from-controllers-to-views-in-aspnet-mvc-tutorial-no-2-.aspx 

In this article we will create a simple customer model, flourish the same with some data and display the same in a view.

MVC Tutorial video 3 Simple model and view example

http://www.dotnetfunda.com/articles/article1317-how-to-create-a-simple-model-in-aspnet-mvc-and-display-the-same-tutorial-.aspx

In this article we will create a simple customer data entry screen with some validation on the view.

MVC tutorial video 4 Simple customer data entry screen.

http://www.dotnetfunda.com/articles/article1388-how-to-create-a-simple-aspnet-mvc-data-entry-screen-tutorial-no-4-.aspx 

This article will demonstrate how to expedite your MVC development process using HTML helper classes.

NA

http://www.dotnetfunda.com/articles/article1415-how-to-create-mvc-model-view-controller-views-faster-by-using-html-helper-.aspx 

This article demonstrates how we can do unit testing in MVC (Model view controller) applications.

NA

http://www.dotnetfunda.com/articles/article1429-how-can-we-do-unit-test-in-mvc-model-view-controller-application-tutoria-.aspx

This article demonstrates how we can define custom routing in MVC applications. NA http://www.dotnetfunda.com/articles/article1485-what-is-mvc-model-view-controller-routing-tutorial-number-7-.aspx


My half life has been spent on writing interview questions for Microsoft technology and I hope I keep writing them. You can see my video tutorial for the same by clicking on .NET,ASP.NET,C#,MVC Interview questions and answers

MVC is all about action which happens via URL and data for those actions is also provided by the URL. It would be great if we can validate data which is passed via these MVC URL’s.

For instance let’s consider the MVC URL http://localhost/Customer/ViewCustomer  . If anyone wants to view customer details for 1001 customer code he needs to enter http://localhost/Customer/ViewCustomer/1001 .

The customer code is numeric in nature. In other words anyone entering a MVC URL like http://localhost/Customer/ViewCustomer/Shiv  is invalid. MVC framework provides a validation mechanism by which we can check on the URL itself if the data is appropriate. In this article we will see how to validate data which is entered on the MVC URL. So let’s start step by step.

Step 1:- Create a simple customer model

The first is to create a simple customer class model which will be invoked by the controller.
public class Customer

{
public int Id { set; get; }
public string CustomerCode { set; get; }
public double Amount { set; get; }
}


Step 2:- Create the controller class


The next step is to create a simple controller class which has collection of the customer model object which was created in step 1.
public class CustomerController : Controller

{
List<Customer> Customers = new List<Customer>();
//
// GET: /Customer/
public CustomerController()
{
Customer obj1 = new Customer();
obj1.Id = 12;
obj1.CustomerCode = "1001";
obj1.Amount = 90.34;

Customers.Add(obj1);

obj1 = new Customer();
obj1.Id = 11;
obj1.CustomerCode = "1002";
obj1.Amount = 91;
Customers.Add(obj1);

}

[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];

return View("DisplayCustomer",objCustomer);
}
}


The controller has a simple ‘DisplayCustomer’ function which displays the customer using the ‘id’ value. This function takes the ‘id’ value and looks up through the customer collection. Below is the downsized reposted code of the function.

[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];

return View("DisplayCustomer",objCustomer);
}


If you look at the ‘DisplayCustomer’ function it takes an ‘id’ value which is numeric. We would like put a validation on this id field with the following constraints:-

• Id should always be numeric.
• It should be between 0 to 99.

We want the above validations to fire when the MVC URL is invoked with data.

Step 3:- Apply validation using regex on the MVC routes

The validation described in the step 2 can be achieved by applying regular expression on the route map. If you go to global.asax file and see the maproute function on the inputs to this function is the constraint as shown in the below figure.



In case you are new to regular expression we would advise you to go through this video on regular expressions http://youtu.be/C2zm0roE-Uc?hd=1

So in order to accommodate the numeric validation we need to the specify the regex constraint i.e. ‘\d{1,2}’ in the ‘maproute’ function as shown below. ‘\d{1,2}’ in regex means that the input should be numeric and should be maximum of length 1 or 2 , i.e. between 0 to 99.

You can specify default values by saying id=0 as shown in the below code snippet. So just in case if some one does not specify the value to the id it will take the value as zero by default.

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer", id 
= 0 }, new { id = @"\d{1,2}" }); // Parameter defaults


Step 4:- Test if it works

So now that we are done with the validation using the ‘maproute’ functions, it’s time to test if these validations work.

So in the first test we have specified valid 1 and we see that the controller is hit and the data is displayed.




If you try to specify value more than 100 you would get error as shown below. Please note that the error is confusing but it’s the effect of the regex validation which is specified on the maproute function.



If you try to specify a non-numeric value you should again get the same error which confirms that our regex validation is working properly.




The most important point to note is that these validations are executed even before the request reaches the controller functions.

So what’s in the next article

One of the crucial things in any website development is defining navigations from one page to the other page. In MVC everything is an action and those actions invoke the views or pages. We can not specify direct hyperlinks like www.questpond.com/home.aspx  , this would defeat the purpose of MVC. In other words we need to specify actions and these actions will invoke the URL’s.

In the next article we will look in to how to define outbound URL in MVC views which will help us to navigate from one page to other page.

 

Page copy protected against web site content infringement by Copyscape

Login to vote for this post.

Comments or Responses

Posted by: Princess on: 2/25/2012 | Points: 25
Please upload all the videos

Login to post response

Comment using Facebook(Author doesn't get notification)