ASP.NET MVC Source Refresh Preview
page 6 of 9
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 37946/ 62

MapRoute Helper Method

URL routing rules within ASP.NET MVC applications are typically declared within the "RegisterRoutes" method of the Global.asax class.

With ASP.NET MVC Previews 1 and 2 routes were added to the routes collection by instantiating a Route object directly, wiring it up to a MvcRouteHandler class, and then by setting the appropriate properties on it to declare the route rules:

Figure 13

The above code will continue to work going forward.  However, you can also now take advantage of the new "MapRoute" helper method which provides a much simpler syntax to-do the same thing.  Below is the convention-based URL route configured by default when you create a new ASP.NET MVC project (which replaces the code above):

Figure 14

The MapRoute() helper method is overloaded and takes two, three or four parameters (route name, URL syntax, URL parameter default, and URL parameter regular expression constraints). 

You can call MapRoute() as many times as you want to register multiple named routes in the system.  For example, in addition to the default convention rule, we could add a "Products-Browse" named routing rule like below:

Figure 15

We can then refer to this "Products-Browse" rule explicitly within our Controllers and Views when we want to generate a URL to it.  For example, we could use the Html.RouteLink view helper to indicate that we want to link to our "Products-Browse" route and pass it a "Food" category parameter using code in our view template like below:

Figure 16

This view helper would then access the routing system and output an appropriate HTML hyperlink URL like below (note: how it did automatic parameter substitution of the category parameter into the URL using the route rule):

Figure 17

Note: with this week's source drop you need to pass-in the controller and action parameters (in addition to the Category param) to the Html.RouteLink() helper to resolve the correct route URL to generate.  The ASP.NET MVC Preview 3 drop in a few weeks will not require this, and allow you to use the Html.RouteLink call exactly as I've written it above to resolve the route.


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 12:05:34 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search