2012-09-24 133 views
1

我有一个Asp.Net Mvc网站有一个列表控制器。路线如下:Asp.Net Mvc路由问题与默认Id

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    new string[] { "MySite.Web.Controllers" } 
); 

非常标准。现在我的列表控制器中有许多控制器操作。我希望能够进入/列出/ 84并将其转到索引行动或/列出/创建,/列出/编辑,/列出/最爱或/列出/其他,并让它去到相应的操作。对于我的大部分路线来说,情况已经如此。这是我的控制器代码:

public ActionResult Index(long? id) 
{ 
    // my code that never gets hit 
} 

我错过了什么吗?

+0

我编辑的问题,告知大家的是,我在控制多个动作。 –

回答

3

你可以定义此为ID的具体路线和约束:

routes.MapRoute(
    "ActionLess", 
    "{controller}/{id}", 
    new { controller = "Home", action = "Index" }, 
    new { id = @"^[0-9]+$" }, 
    new string[] { "MySite.Web.Controllers" } 
); 

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    new string[] { "MySite.Web.Controllers" } 
); 
+0

非常感谢你。确实是优雅的解 –

0

您可以创建两个新的路径为它

对于lisitng /合格标识

routes.MapRoute(
    "lisingid", // Route name 
    "listing/{Id}", // URL with parameters 
     new { controller = "listing", action = "Index", id = UrlParameter.Optional } 
); 

我希望当创建用于导航创建行动

routes.MapRoute(
    "listingCreate", // Route name 
    "listing/Create", // URL with parameters 
     new { controller = "listing", action = "Create" } 
); 

对于指数的行动,这将有助于您。

+0

做到这一点的一种方法。我不认为这是一个不好的解决方案,但如果我有20个不同的行为,那么我将不得不做20种不同的方法。 –