I’ve just added some search functionality to a project of mine which is working correctly. Having just used the SO search, I realised there is one tiny detail which I prefer to my own search and I became curious as to how it is achieved being as I’m also using MVC 3 and Razor for my site.
If I search SO, I’ll end up with a URL such as:
http://stackoverflow.com/search?q=foo
However, searching my own application results in:
http://example.com/posts/search/?searchTerms=foo
Notice the / between search and ?. Although this is purely cosmetic, how can I remove that from the URL so it ends up as:
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’ve tried removing the slash from the route but that gave an error. I also tried adding in a ? instead of the slash but that also gave an error. Would anyone be kind enough to solve this mystery for me?
In fact, when the
searchTermscan be null-or-emptyString, that is not necessary to put it inmapRoute. And when you try to create a link byHtml.ActionLinkorHtml.RouteLink, and pass asearchTermsparameter to it, it will create thesearchTermsas a query-string without any slashes:and in Razor:
and in controller: