2011-03-09 34 views
0

我有航線定義網址:生成使用圖路線默認

routes.MapRoute("CategoryList_CountryLanguage", "Categories/{id}/{urlCategoryName}/{country}/{language}", 
     new { 
      controller = "Categories", 
      action = "Details", 
     }); 

    routes.MapRoute("CategoryList", "Categories/{id}/{urlCategoryName}", 
     new { 
      controller = "Categories", 
      action = "Details", 
      country = "US", 
      language = "EN" 
     }); 

和我使用生成鏈接:

@Html.ActionLink("desc", "Details", "Categories", new { id = item.Id, urlCategoryName = item.UrlFriendlyName}, null) 

並且將所生成的URL的形式爲: /分類/ id/friendly-name

我要生成: /Categories/id/friendl y-name/US/EN

無需在ActionLink調用中指定國家和語言,我不能使用類似的默認值嗎? 簡單的解決方法是在ActionLink調用中指定這些參數,但如果可能,我想避免這種情況。我希望第一個路徑期望在url中指定的值,而第二個路徑在沒有包含在url中時會有默認值,並且會使用它創建新的url,至今沒有運氣,這可能嗎?

+0

你需要傳遞的價值觀,如果你願意,我可以告訴你一個擴展方法這將完成你想要的。 – Paul 2011-03-09 01:13:06

+0

所以你說,不可能使用這樣的默認值來自動生成url – BlackTigerX 2011-03-09 04:14:35

回答

0

可以創建名爲UrlHelpers.cs一個輔助類,看起來像這樣:

public static class URLHelpers { 

     public static string CategoryList(this UrlHelper helper, int id, string urlFirendlyName) { 
      return CategoryList(helper, id, urlFirendlyName, "US", "EN"); 
     } 

     public static string CategoryList(this UrlHelper helper, int id, string urlFirendlyName, string country, string language) 
     { 
      return helper.Action("Details", "Categories", new { id, urlCategoryName = urlFriendlyName, country, language }); 
     } 
} 

然後在你看來,你會這樣稱呼它:

<a href="@Url.CategoryList(item.id, item.UrlFriendlyName)">Some Text</a> 

剛一說明:您想要在你的web.config頁面>命名空間部分添加你的助手的命名空間。所以,如果你增加一個助手文件夾到你的MVC應用程序的根目錄並在其中放置了UrlHelper.cs類你可以這樣:

<pages> 
     <namespaces> 
     <add namespace="System.Web.Helpers" /> 
     <add namespace="System.Web.Mvc" /> 
     <add namespace="System.Web.Mvc.Ajax" /> 
     <add namespace="System.Web.Mvc.Html" /> 
     <add namespace="System.Web.Routing" /> 
     <add namespace="System.Web.WebPages"/> 

     <add namespace="MyProject.Helpers"/> 
     </namespaces> 
</pages>