Question:
I have a route problem (again), I use ASP.NET MVC5, and I have the following route mapped:
routes.MapRoute(
"Search_route",
"Home/Search/{search_input}/{search_input_category}",
new {
controller = "Home",
action = "Search",
search_input = UrlParameter.Optional,
search_input_category = UrlParameter.Optional
}
);
If I apply: Url.Action("Search", "Home", new { search_input = "casa", search_input_category = "vetores" })
my return will be: /Home/Search/home/vectors . But when trying to use this route in the following form:
@using (Html.BeginForm("Search", "Home", FormMethod.Get, new { @class = "search-form" })){
//Todos os campos de input devidamente nomeados
}
When I make the request, my url returns /Home/Search?search_input=Home&search_input_category=vectors That is, the route is correct, but it is not being applied to the <form>
for some reason. Is it possible to apply the route to the form somehow?
Answer:
The problem there is that the routing system chooses the first compatible route to build the route and not the custom one.
To specify a custom route, use the Html.BeginRouteForm()
method. In it you pass the name of the route you created, in this case it is Search_route
.
Example:
@using (Html.BeginRouteForm("Search_route", FormMethod.Get, new { @class = "search-form" }))