How to get Html.BeginForm to GET to correct MVC Route
-
07-07-2019 - |
Question
In my ASP.NET MVC application I have the following GET input field:
<% using (Html.BeginForm("Search", "Products", FormMethod.Get) { %>
<input type="text" name="searchQuery" id="searchQuery" />
<% } %
I want this to go to the route:
routes.MapRoute("ProductSearchRoute",
"Products/Search/{searchQuery}/{pageNumber}",
new { controller = "Products", action = "Search", pageNumber = 1 });
The problem is, it goes to /Products as query string, e.g. Products?searchQuery=Motoroil. How do I get it to use my ProductSearchRoute and instead form /Products/Search/Motoroil ?
Solution
If I understand you correctly, you're trying to dynamically alter the location the form posts to, based on the inputs of the form?
You'll need to use javascript for this, to alter the form's target attribute. The BeginForm() is for rendering the form tag, which from an html perspective, is static.
OTHER TIPS
You could try:
<% using (Html.BeginRouteForm("ProductSearchRoute", FormMethod.Get)) %>
Kindness,
Dan
public ActionResult SearchQuery (string searchQuery)
{
return RedirectToAction (searchQuery, "/Products/Search" );
}
public ActionResult Search (string searchQuery)
{
return View();
}
As @Daniel Elliott suggested, use BeginRouteForm. To get your URL to generate properly, you have to set the routevalues with the same name defined in your route table.
@using (Html.BeginRouteForm("ProductSearchRoute", new { searchQuery= "my query", pageNumber = 1 })
{
}