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)) {
source share