如何在 MVC3 中生成自定义 URL,而不是将我的参数作为查询字符串传递
当我输入 ../Search/Recipes/Deserts/Pie 这样的 URL 时,我可以重定向到该页面(即在 SearchController 中,操作方法将是 Recipes ,参数将是 Deserts & Pie 。
注意:要实现相同的效果我在 Global.asax 中添加了一条路由,如下所示:
routes.MapRoute(
"SearchRecipes",
"Search/Recipes/{category}/{type}",
new { controller = "Search", action = "Recipes", category = "all" , type = ""}
);
但是如何通过我们的代码生成该 URL?当我尝试在 Url.Action 中添加路由值时,它会作为查询字符串出现
。例如,
Url.Action( "Recipes" , "Search" , new { type = item.type, isPie = item.isPie} )
会给我看起来像这样的链接: Search/Recipes ?type=Deserts&isPie=Y
,
但我想生成像 Search/Recipes/Deserts/Y
这样的 url
。 基本上我不想
将参数作为查询字符串传递,但想遵守 \ 分隔的值。
When I type the URL like ../Search/Recipes/Deserts/Pie, I can get redirected to that page (i.e in SearchController, action method would be Recipes & parameters would be Deserts & Pie .
NB: To achieve the same I ve added a route in my Global.asax, that looks like :
routes.MapRoute(
"SearchRecipes",
"Search/Recipes/{category}/{type}",
new { controller = "Search", action = "Recipes", category = "all" , type = ""}
);
But how to generate that URL through our code? When I try to add a route value in Url.Action, it comes as a query string.
For example,
Url.Action( "Recipes" , "Search" , new { type = item.type, isPie = item.isPie} )
would give me link that looks like : Search/Recipes?type=Deserts&isPie=Y
,
but I want to generate url like Search/Recipes/Deserts/Y
.
Please let me know how we can achieve the same?
Basically I dont want to pass my parameters as query string, but want to adhere to \ separated values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
定义路由时未指定的任何查询参数都将添加为 ?param=value
Try
Any query parameter not specified when defining a route will be added as ?param=value
您可以使用 UrlHelper.RouteUrl 方法
You can use the UrlHelper.RouteUrl method