2011-03-09 32 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>