Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET MVC - Routing

DZone's Guide to

ASP.NET MVC - Routing

·
Free Resource
One of the core features of ASP.NET MVC that makes everything “just work” is the concept of routing.  By specifying ahead of time what a route looks like, we can create links that look like regular URLs with no parameters that behave like parameterized URLs on the server.

The magic for this all happens in Global.asax.cs (or .vb if you are using Visual Basic)

Open up the project you created last week and take a look at the Global.asax.cs file and you will find the following code:

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

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = "" } // Parameter defaults
);

}

The first line,

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

is saying, “ignore anything that has an AXD extension.

The second line,

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = "" } // Parameter defaults
);

Is saying, “create a route named default that interprets a URL in the form of Directory/Directory/Directory and have it call the Controller class using the first directory name, a method in that controller class using the second directory name and a parameter using the third directory name.  If nothing is passed that matches, then just call the ‘Index’ method of the ‘Home’ controller without any parameters.”

In the sample code, you’ll see that ID is an integer.  But, there is no reason why this parameter could not be a string.  There is also no reason why you couldn’t have multiple parameters if you needed or multiple routes if that makes sense.  You do, however, need at least one route.

You may want to consider NOT using integers for parameters in this scheme.  You may need a lookup table to achieve this but the advantage of not using integers is that your URLs look more “normal” and will be easier for the site visitor to remember.

Which would you rather remember?

http://somesite.com/Recipes/Display/ChickenSalad

or

http://somesite/Recipes/Display/23 ?

 

Topics:

Published at DZone with permission of Dave Bush, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}