Joh*_*n H 4 c# url asp.net-mvc slash query-string
我刚刚为我正在正常工作的项目添加了一些搜索功能.刚刚使用SO搜索,我意识到有一个小细节,我更喜欢自己的搜索,我很好奇它是如何实现的,因为我也使用MVC 3和Razor为我的网站.
如果我搜索SO,我最终会得到一个URL,例如:
http://stackoverflow.com/search?q=foo
Run Code Online (Sandbox Code Playgroud)
但是,搜索我自己的应用程序会导致:
http://example.com/posts/search/?searchTerms=foo
Run Code Online (Sandbox Code Playgroud)
请注意/之间search和?.虽然这纯粹是装饰性的,但如何从URL中删除它,最终结果如下:
http://example.com/posts/search?searchTerms=foo
Run Code Online (Sandbox Code Playgroud)
这是我的搜索路线:
routes.MapRoute(
"SearchPosts",
"posts/search/{*searchTerms}",
new { controller = "Posts", action = "Search", searchTerms = "" }
);
Run Code Online (Sandbox Code Playgroud)
我试过从路线中删除斜线,但这给出了一个错误.我也尝试添加一个?而不是斜杠,但也出错了.有人会善意为我解决这个谜吗?
实际上,当searchTerms可以为null-or-emptyString时,不需要将其放入mapRoute.当您尝试通过Html.ActionLink或创建链接Html.RouteLink,并将searchTerms参数传递给它时,它将创建searchTerms一个没有任何斜杠的查询字符串:
routes.MapRoute(
"SearchPosts",
"posts/search",
new { controller = "Posts", action = "Search"
/* , searchTerms = "" (this is not necessary really) */ }
);
Run Code Online (Sandbox Code Playgroud)
在剃刀:
// 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
Run Code Online (Sandbox Code Playgroud)
// 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
}
Run Code Online (Sandbox Code Playgroud)
在控制器中:
public class PostsController : Controller {
public ActionResult Search(string searchTerms){
if(!string.IsNullOrWhiteSpace(searchTerms)) {
// TODO
}
}
}
Run Code Online (Sandbox Code Playgroud)