gpt4 book ai didi

c# - 删除操作和查询字符串之间的斜杠(就像 SO 的搜索行为一样)

转载 作者:太空狗 更新时间:2023-10-30 00:56:23 25 4
gpt4 key购买 nike

我刚刚将一些搜索功能添加到我的一个正常工作的项目中。刚刚使用了 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 = "" }
);

我已经尝试从 route 删除斜线,但出现了错误。我还尝试添加一个 ? 而不是斜杠,但这也给出了一个错误。有好心人帮我解开这个谜团吗?

最佳答案

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

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

在 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

}

在 Controller 中:

public class PostsController : Controller {
public ActionResult Search(string searchTerms){
if(!string.IsNullOrWhiteSpace(searchTerms)) {
// TODO
}
}
}

关于c# - 删除操作和查询字符串之间的斜杠(就像 SO 的搜索行为一样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com