MVC Routing get rid of /Index in URL

不打扰是莪最后的温柔 提交于 2019-12-12 10:59:11

问题


I have a dynamic list of ActionLinks generated at run time like this:

@Html.ActionLink(x.Name, "Index", "User", new { x.ID }, null)

so I'm hitting the Index method on the User controller.

I also have my RouteConfig.cs (it's an MVC4 app) set as follows:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }
        );
    }

This gives me the link server/application/User/Index/1 in my list of links.

What do I need to do in the list generation and / or routing file to change this to server/application/User/1?


回答1:


Add a route that doesn't need an action but won't clash with other routes

routes.MapRoute("User", "User/{id}", 
                         new { controller = "User", action = "Index" });


来源:https://stackoverflow.com/questions/13568119/mvc-routing-get-rid-of-index-in-url

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