views:

36

answers:

2

Given these routes:

routes.MapRoute("Test", "test", new { controller = "Test", action = "Index" });
routes.MapRoute("Default", "{controller}/{action}/{id}", 
  new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

If I call RedirectToRoute("Default") from the Index action of the TestController it redirects to /test but I expected it to redirect to /

I checked the result of calling RedirectToRoute("Default") before returning it during a debugging session.

RedirectToRouteResult result = RedirectToRoute("Default");

It has a property RouteName with a value "Default" and a property RouteValues with no elements (Count = 0). I checked using Reflector, and null is passed internally as the RouteValueDictionary.

Again, I would expect that given the defaults for the route defined in my application, it would redirect to Index view on the HomeController.

Why doesn't it redirect to /?

+1  A: 

Without looking at the actual code to see what is going on it can be a bit tricky to know why, but this forum post does shed some light. The answerer says that under the covers it might be creating a RouteValueDictionary which would contain the controller and action you are currently in, which in your case would be a controller of Test and an action of Index. Then, when you call RedirectToRoute("Default"), the controller and the action in the RouteValueDictionary will be used when matching the default route and you will be taken to the Index action in your Test controller.

Now you could always do a Redirect("/") to take you to the main page of your site.

amurra
+2  A: 

The RouteValueDictionary filled in to the current action is being used to fill in the Controller, Action, ID. This is usually the functionality you want and lets you do things like <%:Html.ActionLink("MyAction")%> without needing to specify your controller in a view.

To force it to the complete fall back default just use:

RedirectToRoute("default", null");

The second argument is for your routevalues and by specifying it you override the preexisting values.

However I would say the preferred way would be to have a Home route which will not take any parameters. This means your redirects will not need a load of nulls floating around and a call to RedirectToRoute("Home") is also nice and explicit.

Chao