ASP.NET MVC:url 路由与查询字符串 [英] ASP.NET MVC: url routing vs querystring
问题描述
我有一个类似于 /Comments/Search/3
的页面,我在其中搜索并显示主题3"的所有评论.
I have a page routed like /Comments/Search/3
where i search and display all the comments of the thread "3".
我正在添加排序功能(按日期、作者等).处理它的最佳方法是什么?/Comments/Search/3/Sort/Author
或 /Comments/Search/3?sort=author
?
I'm adding a sort function (by date, author etc). What is the best way to handle it? /Comments/Search/3/Sort/Author
or /Comments/Search/3?sort=author
?
如何在MVC中自动处理querystring sort=author作为参数?
How do I automatically handle the querystring sort=author as a parameter in MVC?
谢谢
推荐答案
我更喜欢:/Comments/Search/3?sort=author.查询字符串是传递编程参数的好地方,尤其是在参数(如本例中)对于 SEO 目的不重要的情况下.如果该参数作为搜索词具有某种语义意义,则第一个 URL 会更好.
I prefer: /Comments/Search/3?sort=author. The querystring is a good place to pass in programmatic parameters, especially if the parameter (like in this case) is not important for SEO purposes. If the parameter had some semantic meaning as a search term, the first URL would be better.
在控制器方法中,您可以使用以下内容:
In a controller method you can use something like this:
public ActionResult Search(int id, string sort)
ASP.NET MVC 将自动将查询字符串值连接到您的方法的参数.
ASP.NET MVC will automatically wire up querystring values to the parameters of your method.
使用以下路线
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Comments", action = "Search", id = "" } // Parameter defaults
);
/Comments/Search/3?sort=author 将调用 Search(3, "author")
/Comments/Search/3?sort=author will call Search(3, "author")
/Comments/Search/3 将调用 Search(3, null)
/Comments/Search/3 will call Search(3, null)
请记住,id 是必需的,因此此 url 将失败:/评论/搜索
Keep in mind that id is mandatory so this url will fail: /Comments/Search
这篇关于ASP.NET MVC:url 路由与查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!