生成使用 MapRoute 默认值的 url
我定义了这些路由:
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)
并且生成的网址格式为: /Categories/id/friend-name
我想生成: /Categories/id/friend-name/US/EN
无需在 ActionLink 调用中指定国家/地区和语言,我不能使用这样的默认值吗? 简单的解决方法是在 ActionLink 调用中指定这些参数,但我希望尽可能避免这种情况。我的希望是,第一个路由需要 url 中指定的值,而第二个路由在未包含在 url 中时具有默认值,并使用它来创建新的 url,到目前为止没有运气,这可能吗?
I have these routes defined:
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"
});
and I'm generating links using:
@Html.ActionLink("desc", "Details", "Categories", new { id = item.Id, urlCategoryName = item.UrlFriendlyName}, null)
and the generated urls are in the form:
/Categories/id/friendly-name
I want to generate:
/Categories/id/friendly-name/US/EN
without having to specify the country and language in the ActionLink call, can't I use defaults like that?
The easy workaround is to specify those parameters in the ActionLink calls, but I would like to avoid that if possible. My hope is that the first route expects the values specified in the url, while the second has the defaults when not included in the url and would use that to create new urls, no luck so far, is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个名为 UrlHelpers.cs 的帮助程序类,如下所示:
然后在您看来,您可以这样调用它:
只是注意:您需要将帮助程序的命名空间添加到页面 > 中的 web.config 中。命名空间部分。因此,如果您将 Helpers 文件夹添加到 MVC 应用程序的根目录并将 UrlHelper.cs 类放入其中,您将添加:
You can create a helper class called UrlHelpers.cs that looks like this:
Then in your view you would call it like this:
Just a note: You will want to add the namespace of your helper to your web.config in the pages > namespaces section. So if you add a Helpers folder to the root of your MVC app and place the UrlHelper.cs class in it you would add: