Set default action (instead of index) for controller in ASP.NET MVC 3

Cody picture Cody · Oct 3, 2012 · Viewed 31.5k times · Source

I have a controller called Dashboard with 3 actions: Summary, Details, and Status, none of which take an ID or any other parameters. I want the URL /Dashboard to route to the Summary action of the Dashboard controller, as /Dashboard/Summary does, but I can't figure out the correct way to add the route. In Global.asax.cs, I have the following:

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

routes.MapRoute(
    "/Dashboard",
    "Dashboard",
    new { controller = "Dashboard", action = "Summary" }
    );

For the second part, I've also tried:

routes.MapRoute(
    "/Dashboard",
    "{controller}",
    new { controller = "Dashboard", action = "Summary" }
    );

and

routes.MapRoute(
    "/Dashboard",
    "{controller}",
    new { action = "Summary" }
    );

but I always get a 404 when trying to access /Dashboard. I'm pretty sure I'm missing something about the format for the parameters to MapRoute, but I don't know what it is...

Answer

Gromer picture Gromer · Oct 3, 2012

Move your Dashboard route in front of the Default route:

routes.MapRoute(
    "Dashboard",
    "Dashboard/{action}",
    new { controller = "Dashboard", action = "Summary" }
);

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

The order of routes changes everything. Also, notice the changes I made to the Dashboard route. The first parameter is the name of the route. Second is the URL, which match URLs that start with Dashboard, and allows for other actions in your Dashboard controller. As you can see, it will default to the Summary action.