In part 1 of this blog we set up a dynamic menu loaded from a model, but we did nothing with routing. If you open up the _departments.cshtml file we created before you’ll see that we created the links like this
@Html.ActionLink(department.DepartmentName, "", department.DepartmentName)
This is defining a link that is calling no action with a controller name of the department name. Now we don’t have any controllers with the department names and because we want this solution to be dynamic we aren’t going to create any. Instead what we will do is add some new routes to the RouteCollection that will route all clicks to the index view of the HomeController. To do this we will make some changes to the RouteConfig class. Open up the RouteConfig.cs file and add the following class extension:
public static class RouteCollectionExtensions
public static Route MapRouteWithName(this RouteCollection routes, string name, string url, object defaults)
Route route = routes.MapRoute(name, url, defaults);
route.DataTokens = new RouteValueDictionary();
A class extension allows us to add functionality to an existing class. In this case we are adding the ability to add DataToken information when we map a route. The reason for this will become apparent later on. Next we are going to modify the RegisterRoutes method to obtain a list of departments and then add a new route for each by using our class extension. The whole code should look like this
You will notice that when we map the route we are sending a new object default of the HomeControllers index action. If you run the project now and click on one of the department links you should find that it will load up the Index view of the HomeController but if you look at the URL it will have the department name as the controller.
This is still not that useful, but in the next part of this I will show you how to use the DataTokens in order to load dynamic content.