Remove the slash between the action and the querystring (for example, how SO searches)

I just added some search features to my project that works correctly. Just using the SO search, I realized that there is one tiny detail that I prefer for my own search, and I was curious how this is achieved, since I also use MVC 3 and Razor for my site.

If I search for SO, I will have a url like this:

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

However, searching for my own application results in:

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

Pay attention to / between search and ? . Although this is purely cosmetic, how can I remove this from the url, so it ends up like:

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

This is my search route:

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

I tried to remove the slash from the route, but this gave an error. I also tried adding in ? instead of a slash, but also gave an error. Will anyone be kind enough to solve this secret for me?

+4
source share
1 answer

In fact, when searchTerms can be null-or-emptyString, there is no need to insert it into mapRoute . And when you try to create an Html.ActionLink or Html.RouteLink and pass the searchTerms parameter to searchTerms , it will create searchTerms as a query string without any slashes:

 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 the controller:

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

All Articles