2011-08-15 45 views
0

我定义了一个新的路由(见下文)。当我启动应用程序,我想用默认:在ASP.NET MVC中定义路由

  • 返回首页/索引
  • 如果我去/客户/详细信息/ mycode的得到“mycode的”

当我使用这个配置,我开始在Home/Index上,但是/ Customer/Detail/MyCode始终给出一个空值。

如果我反了routes.MapRoute,我有:

  • 默认情况下,我去/客户/详细信息和我mycode的值所有的时间(无空anymoe)
  • 我不开始/主页/索引

任何想法?

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
); 

routes.MapRoute(
    "CustomerDetail", 
    "{controller}/{action}/{code}", 
    new { controller = "Customer", action = "Detail", code = UrlParameter.Optional } 
); 

回答

3

一个路由就足够了:

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{code}", // URL with parameters 
    new { controller = "Home", action = "Index", code = UrlParameter.Optional } // Parameter defaults 
); 

当请求Home/Index这将调用上HomeControllerIndex行动,传递null作为code参数,当你要求Customer/Detail/MyCodeDetail动作会在CustomerController上调用并通过code=MyCode

你越来越空的理由是,无论你的路由是等价的,这意味着它们是这意味着对于这两个URL的第一路径匹配形式Controller/Action/SomeCode的,但参数被称为的id代替code所以你得到code=null。另一种可能性是只需将默认路由的是:

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
); 

,然后将参数重命名为Detail行动ID:

public ActionResut Detail(string id) 
{ 
    // if you request Customer/Detail/MyCode the id parameter will equal MyCode 
} 
+0

首页/索引将不会被接受的值是指我会去/ Customer/Detail/MyCode ...我不想那样。我开始申请,我必须保持/ Home/Index。后来,我会有像/ Product/Detail/MyCode Keep ID这样的东西不相关,它不是一个ID它是一个代码.. –