简体   繁体   中英

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

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

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.

您需要最后声明“默认”全部捕获路由。

This set default Action for any Controller asp.net:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM