ASP.Net MVC: Routes

What are Routes?

Routes define the structure of an url within a ASP.Net MVC. In ASP.Net MVC a url does not match a physical file on a harddisk, the url will be transformed into an controller action. Routes are defined in the global.asax file.

The default route

The default route has a very common layout:

{controller}/{action}/{id}

Every tag wrapped into { } defines a segment of the request. For sample

http://myhost/Customer/Edit/123

will invoke the Edit() method on the CustomerController and pass 123 as parameter.

An other valid url will be

http://myHost/

witch invokes the Index method on the HomeController without passing a parameter.

The third case is

http://myHost/Customer/

By accessing this url you will get the View returned by the Index() Method on the Customer Controller without passing a parameter.

As said by the ASP.Net MVC team the default route matches in 85% of user requirements but what about the other 15%?

For these 15% you can extend the routemap and add custom routes.

Creating a custom route

Custom routes have to be declared in global.asax too.  If you decide to add a custom route, its important to paste the custom route before the default route.

I will provide only a small example cause creating routes in MVC is a very, very simple task. Just open Global.asax and look for the RegisterRoutes Method.

Startpoint for adding custom routes is between the IgnoreRoute() and the MapRoute("Default") calls.

You can add your own route by using the MapRoute() Method on a RouteCollection Instance.

routes.MapRoute( "BlogArchive",
                "{controller}/{year}/{month}/",
                new
                {
                    controller = "Blog",
                    action = "Archive",
                    year = "",
                    month = "";
                }
                );

What have we done here?

Now, I created a new route which is named "BlogArchive". As the pattern defines all urls matching

{controller}/{year}/{month}/

will be parsed using the the BlogArchive route

 

Published Mittwoch, 25. März 2009 10:39 von ThorstenHans
Abgelegt unter: , , ,

Kommentare

Keine Kommentare

Kommentar abgeben

(verpflichtend) 
(verpflichtend) 
(optional)
(verpflichtend)