I want to use BegingForm with Get method and this is what I do
@using (Html.BeginForm("Search","Home",FormMethod.Get))
{
//My input elements
}
public class HomeController : Controller
{
public ActionResult Search(string queryString)
{
}
}
but query string always comes back as null. I think, I need to do something with route but no luck
routes.MapRoute(
"SearchRoute", // Route name
"Home/Search{queryString}", // URL with parameters
new { controller = "Home", action = "Search", filter = UrlParameter.Optional } // Parameter defaults
);
Obviously, the coming url to the server is something like
Home/Search?query=”blah”&query2=”blah”&query3=”blah”
What am I doing wrong? What is the correct way to get the query parameters in my controller when I want to use get with beginform?
Also, what if the content of my BeginForm can change and so the query string parameter names could be different depending on the rendered page but I want one Search method that analyze the query string and do the right thing?
Also, is a way for them to query parameters to come in a dictionary?
That’s how HTML
<form>with method GET works and this has nothing to do with ASP.NET MVC, it’s plain HTML. You can’t do much about it other than having your controller action look like this:Where
SearchViewModelwill contain properties for each input field on this form. Also you don’t need thisSearchRouteas it won’t work that way.This being said you could probably use javascript in order to subscribe for the
onsubmitevent of the form, cancel the default submission (which exhibits the behavior you are observing currently), manually fetch all the values inside your form and then manually generate the url you want and redirect to it usingwindow.location.href = '....';. I am mentioning this only for completeness but absolutely not as something that I recommend or that you should ever do.