Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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...

like image 245
Cody Avatar asked Oct 03 '12 19:10

Cody


2 Answers

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.

like image 149
Gromer Avatar answered Sep 29 '22 12:09

Gromer


You need to declare the "Default" catch-all route last.

like image 34
tuxedo25 Avatar answered Sep 29 '22 11:09

tuxedo25