我刚刚为我的一个正常工作的项目添加了一些搜索功能。刚刚使用了SO搜索,我意识到有一个小细节,我更喜欢我自己的搜索,我变得好奇它是如何实现的,因为我也使用MVC 3和Razor为我的网站。
如果我搜索SO,我将得到一个URL,如:http://stackoverflow.com/search?q=foo
但是,搜索我自己的应用程序的结果是:
http://example.com/posts/search/?searchTerms=foo
注意search
和?
之间的/
。虽然这纯粹是装饰,但我如何从URL中删除它,使其最终为:
http://example.com/posts/search?searchTerms=foo
这是我的搜索路径:
routes.MapRoute(
"SearchPosts",
"posts/search/{*searchTerms}",
new { controller = "Posts", action = "Search", searchTerms = "" }
);
我已经尝试从路由中删除斜杠,但这会产生一个错误。我还尝试添加?
而不是斜杠,但这也给出了一个错误。有人愿意为我解开这个谜团吗?
事实上,当searchTerms
可以为null或emptystring时,没有必要将其放在mapRoute
中。当您尝试通过Html.ActionLink
或Html.RouteLink
创建链接时,并将searchTerms
参数传递给它,它将创建searchTerms
作为没有任何斜杠的查询字符串:
routes.MapRoute(
"SearchPosts",
"posts/search",
new { controller = "Posts", action = "Search"
/* , searchTerms = "" (this is not necessary really) */ }
);
and in Razor:
// for links:
// @Html.RouteLink(string linkText, string routeName, object routeValues);
@Html.RouteLink("Search", "SearchPosts", new { searchTerms = "your-search-term" });
// on click will go to:
// example.com/posts/search?searchTerms=your-search-term
// by a GET command
// or for forms:
// @Html.BeginRouteForm(string routeName, FormMethod method)
@using (Html.BeginRouteForm("SearchPosts", FormMethod.Get)) {
@Html.TextBox("searchTerms")
<input type="submit" value="Search" />
// on submit will go to:
// example.com/posts/search?searchTerms=*anything that may searchTerms-textbox contains*
// by a GET command
}
and in controller:
public class PostsController : Controller {
public ActionResult Search(string searchTerms){
if(!string.IsNullOrWhiteSpace(searchTerms)) {
// TODO
}
}
}