2013-05-26 73 views
0

變量重用這是我RouteConfig.cs生成錯誤傳出URL在MVC 4

routes.MapRoute(null, 
         "{controller}/Page{page}", 
         new {controller = "Product", action = "Index", category = (string) null}, 
         new {page = @"\d+"} 
      ); 

     routes.MapRoute(null, 
         "{controller}/{category}", 
         new {controller = "Product", action = "Index", page = 1} 
      ); 

     routes.MapRoute(null, 
         "{controller}/{category}/Page{page}", 
         new {controller = "Product", action = "Index"}, 
         new {page = @"\d+"} 
      ); 

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

這裏是生成URL代碼:

@Html.ActionLink("View Cart", "Index", "ShoppingCart", null, new { @class = "btn btn-orange" }) 

它工作得很好,當我瀏覽到,例如,Product/Page2,Product/Laptop,Product/Laptop/Page2。問題是,無論何時我的當前URL包含Page段,它都會嘗試重新使用該段來生成傳出網址。所以,如果我在Product/Page2上面生成的URL將是ShoppingCart/Page2。我不知道如何避免這種情況。

請幫幫我。非常感謝。

編輯!

我找到了解決方法。除了使用ActionLink,我使用RouteLink這樣的:

@Html.RouteLink("View Cart", "Default", new { controller = "ShoppingCart", action = "Index" }, new { @class = "btn btn-orange" }) 

但我還是想用ActionLink,所以請幫助我。

編輯!

當我生成到ShoppingCart/Checkout的鏈接時,解決方法不起作用。它仍然帶我到行動在ShoppingCart控制器。

+0

對於購物車鏈接,您定位的是哪條路線? –

+0

最後一個,只是正常模式,控制器/操作。 – AnhTriet

+0

但它匹配在第二條路線本身。你需要用更多的約束來縮小第二個映射或重新排列映射,看看它是否有幫助。 –

回答

0

創建特定於ShoppingCart的新路線模式,並使其成爲的首條路線,並將其置於頂部

routes.MapRoute(null, 
        "ShoppingCart/{action}", 
        new {controller = "Product"}); 
     ); 

作爲一項規則,所有的具體路線應該是第一位的。

0

這是因爲路由系統在嘗試匹配路由時嘗試評估段變量的值的方式。

所以當呈現鏈接調用帶有下列參數發生:

@Html.ActionLink("View Cart", "Index", "ShoppingCart", null, new { @class = "btn btn-orange" })

框架與模板評估路由時

{controller}/Page{page}

將解決controller段變量爲ShoppingCart然而,當它無法找到page段變量的值(通過任何方法調用中的參數),它將嘗試並從ViewContext中的RouteData對象中解析該值。由於您已導航到Product/Page2,路由值字典中的當前值page2

您可以在渲染該視圖時查看ViewContext.RouteData.Values["page"]的值來檢查此問題。