URL Routing in MVC

This post gives a quick insight of URL Routing in MVC.

Overview

  • A Route is a URL Pattern mapped to a handler. A Handler can be physical file or a class file, that does processing
  • URL routing is about freedom from URLs referring to physical files in a web application.
  • In an MVC URL Routing, Actions are mapped to respective Controllers.

Example :

Traditional URL mapping (Web Forms Application) : “localhost/Vehicle/Detail.aspx?VehicleID=12″

This narrates that our web application contains a directory named “Vehicle” & within this folder we have a physical file “Detail.aspx”

URL Routing in MVC  Application : “localhost/Vehicle/Detail/12″

This narrates that our MVC application has a controller “VehicleController” having an Action “Detail”

When we create an MVC 4 web-application it adds following piece of code in RouteConfig.


public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
 

How It works.

Our default routing contains  3  parameters

  1. {controller}  : Name of controller class
  2. {action} :  Name of Action within the controller class
  3. {id} : Parameter needed to process Action

For each incoming request , the MVC framework first locates the controller file, “HomeController”  & then locates the Action “Index” within the controller. Finally It passes parameter {id} to execute located Action.

It is important to note that we don’t need to mention full name of controller as it automatically appends “Controller”  to “Home” & starts locating “HomeController”

Reference :

http://msdn.microsoft.com/en-us/library/cc668201.ASPX

About these ads

Tagged: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: