2011-06-20 95 views
0

使用這條路線:MVC鏈接創建

routes.MapRoute(
     "PartListRoute", 
     "Products/PartList/{Manufacturer}/{Product}/{PartNumber}", 
     new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional, PartNumber = "" } 
    ); 

我試圖創建一個鏈接從/產品/ PARTLIST到去/產品/ PARTLIST/Manufacturer1根據製造商的列表從數據庫中抽取。 mfr.Name是製造商的名稱。

路線應導致的URL像下面

  • /產品/ PARTLIST/
  • /產品/ PARTLIST/Manufacturer1/
  • /產品/ PARTLIST/Manuracturer3 /產品1/
  • /Products/PartList/Manuracturer2/Product4/DN-438

我最近來的是

@Html.RouteLink(mfr.Name, "PartListRoute", new { Manufacturer = mfr.Name}) 

它將製造商名稱放在文本中,但不會將其添加到URL中。我覺得我假設了一些有關路線和鏈接的事情,但這不是事實。

實際上是否有方法使用Route來生成正確格式的新鏈接?

回答

0

萬一有人遇到這個問題,我終於偶然發現了這篇文章,指出當你有連續的可選URL參數時會出現一個錯誤。

http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

我不會要求我完全理解的解釋,但創建都指向回原來的控制器的其他途徑似乎已經解決了這一問題:

 routes.MapRoute(
      "PartListRoute", 
      "Products/PartList/{Manufacturer}", 
      new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
      "PartListRoute2", 
      "Products/PartList/{Manufacturer}/{Product}", 
      new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
      "PartListRoute3", 
      "Products/PartList/{Manufacturer}/{Product}/{PartNumber}", 
      new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional, PartNumber = "" } 
     );