我的路由如何使用ASP MVC3在URL中间使用可选参数?

par*_*eer 5 asp.net-mvc-3

我希望我的URL使用约定:

/{controller}/{id}/{action}
Run Code Online (Sandbox Code Playgroud)

而不是

/{controller}/{action}/{id}
Run Code Online (Sandbox Code Playgroud)

我尝试按如下方式设置路线:

routes.MapRoute(
            "Campaign",
            "{controller}/{action}/{id}",
            new { controller = "Campaign", action = "Index", id = UrlParameter.Optional } 
        );
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为我无法使id参数可选.

以下网址有效:

/campaign/1234/dashboard
/campaign/1234/edit
/campaign/1234/delete
Run Code Online (Sandbox Code Playgroud)

但这些网址不会:

/campaign/create
/campaign/indexempty
Run Code Online (Sandbox Code Playgroud)

MVC只需要Index两者.我究竟做错了什么?

Joh*_*ers 7

我想你可能需要两条不同的路线.

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

routes.MapRoute(
            "Campaign",
            "{controller}/{action}",
            new { controller = "Campaign", action = "Index" } 
        );
Run Code Online (Sandbox Code Playgroud)