4

我刚刚在我的一个工作正常的项目中添加了一些搜索功能。刚刚使用了SO 搜索,我意识到有一个小细节我更喜欢我自己的搜索,我对它是如何实现的感到好奇,因为我也在为我的网站使用MVC 3Razor

如果我搜索SO,我最终会得到一个 URL,例如:

http://stackoverflow.com/search?q=foo

但是,搜索我自己的应用程序会导致:

http://example.com/posts/search/?searchTerms=foo

注意和/之间。虽然这纯粹是装饰性的,但我怎样才能从 URL 中删除它,所以它最终是:search?

http://example.com/posts/search?searchTerms=foo

这是我的搜索路线:

routes.MapRoute(
    "SearchPosts",
    "posts/search/{*searchTerms}",
    new { controller = "Posts", action = "Search", searchTerms = "" }
);

我尝试从路线中删除斜线,但这给出了错误。我还尝试添加 a?而不是斜杠,但这也给出了错误。有人愿意为我解开这个谜吗?

4

1 回答 1

6

事实上,当searchTerms可以是 null-or-emptyString 时,就没有必要将它放入mapRoute. 当您尝试通过Html.ActionLinkor创建链接Html.RouteLink并将searchTerms参数传递给它时,它将创建searchTerms为不带任何斜杠的查询字符串:

routes.MapRoute(
    "SearchPosts",
    "posts/search",
    new { controller = "Posts", action = "Search"
    /* , searchTerms = "" (this is not necessary really) */ }
);

在剃刀中:

// 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

}

在控制器中:

public class PostsController : Controller {
    public ActionResult Search(string searchTerms){
        if(!string.IsNullOrWhiteSpace(searchTerms)) {
            // TODO
        }
    }
}
于 2011-10-25T00:06:34.287 回答