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

天大地大妈咪最大 提交于 2019-11-30 21:37:53

问题


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


回答1:


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.




回答2:


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




回答3:


This set default Action for any Controller asp.net:

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


来源:https://stackoverflow.com/questions/12715667/set-default-action-instead-of-index-for-controller-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!