How to get Html.BeginForm to GET to fix MVC route

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" />
<% } %

      

code>

I want this to move to a route:



routes.MapRoute("ProductSearchRoute", 
    "Products/Search/{searchQuery}/{pageNumber}", 
new { controller = "Products", action = "Search", pageNumber = 1 });

      

code>

The problem is that it goes to / Products as a query string, eg. Products? SearchQuery = motor. How can I use it in ProductSearchRoute and shape / Products / Search / Motoroil instead?

+2


source to share


4 answers


If I understand you correctly, are you trying to dynamically change the location of form posts based on the form input?



For this you need to use javascript to change the target attribute of the form. BeginForm () is for rendering a form tag which is static in terms of html.

+3


source


You may try:

<% using (Html.BeginRouteForm("ProductSearchRoute", FormMethod.Get)) %>

      



Kindness,

Dan

+1


source


public ActionResult SearchQuery (string searchQuery)
{
    return RedirectToAction (searchQuery, "/Products/Search" );
}

public ActionResult Search (string searchQuery)
{
    return View();
}

      

+1


source


As @Daniel Elliott suggested, use a BeginRouteForm. In order for your URL to be generated correctly, you must set the route values ​​with the same name defined in the route table.

@using (Html.BeginRouteForm("ProductSearchRoute", new { searchQuery= "my query", pageNumber = 1 })
{

}

      

0


source







All Articles