4

正しく機能している私のプロジェクトにいくつかの検索機能を追加しました。SO検索を使用したばかりですが、自分の検索よりも細かい部分が1つあることに気付き、サイトにMVC 3Razorも使用しているので、それがどのように達成されるのか興味がありました。

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 = "" }
);

ルートからスラッシュを削除しようとしましたが、エラーが発生しました。?スラッシュの代わりに追加しようとしましたが、それでもエラーが発生しました。誰かが私のためにこの謎を解くのに十分親切でしょうか?

4

1 に答える 1

6

実際、searchTermsがnullまたはemptyStringである可能性がある場合、それをに入れる必要はありませんmapRouteHtml.ActionLinkまた、またはでリンクを作成し、それにパラメータをHtml.RouteLink渡そうとすると、スラッシュなしでクエリ文字列としてが作成されます。searchTermssearchTerms

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 に答える