Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 29888 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET MVC > How to validate data provided in MVC URL’s (MVC Tutorial number 8)?

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

Article posted by Questpond on 8/16/2011 | Views: 7966 | Category: ASP.NET MVC | Level: Advance | Points: 250 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.

 

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:0 year(s)
Home page:http://www.questpond.com
Member since:Wednesday, September 03, 2008
Level:Starter
Status: [PanelMember] [Member] [Microsoft_MVP] [MVP] [Administrator]
Biography:

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers

 Responses
Posted by: Princess | Posted on: 25 Feb 2012 04:08:50 AM | Points: 25

Please upload all the videos

>> Write Response - Respond to this post and get points
Related Posts

As I found many of MVC article but I don't find any article with database interaction with simple functionality. That's the reason I come out with this article.

In the previous ASP.NET MVC tutorial we saw how we can create a simple ASP.NET MVC web application. In case you have missed the same do refer ASP.NET MVC tutorials. In this session we will see how we can pass data from controller to views using view data.

In this article we will try to understand how we can use data annotations for doing validations in MVC web application.

This is the 10thMVC (Model view controller) tutorial and in this article we will try to understand how we can improve reusability using partial views.

In this article we will try to understand what are the different events which takes place right from the time the user sends a request, until the time request is rendered on the browser. So we will first try to understand the two broader steps of an ASP.NET request and then we will move in to different events emitted from ‘HttpHandler’, ‘HttpModule’ and ASP.NET page object. As we move in this event journey we will try to understand what kind of logic should go in each every of these events.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/28/2012 11:55:36 AM