Reputation: 6180
I am unable to post data from a form to a controller action. I've created the form with HTML.BeginForm() and I have a controller which works fine when I manually create the query string, but I don't understand how to make a form work with my controller action.
<form class="navbar-form navbar-left">
<div class="form-group>
@using (Html.BeginForm("GeneralSearch", "Search", FormMethod.Post))
{
@Html.TextBox("searchString")
<button type="submit" class="default">Submit</button>
}
</div>
</form>
And then in my controller I currently have the HttpGet
attribute that ASP.NET automatically placed there. However, if I change it to HttpPost
the problem still occurs.
[HttpGet]
public ActionResult GeneralSearch(string searchString)
{
return View("SearchResult", viewModel);
}
When I enter text and submit the form, a network request is sent to:
http://localhost:64562/?searchString=test
Which simply loads the default controller and action instead of the "Search" controller I specified in the using
statement. How do I correctly post to a specific action?
Upvotes: 0
Views: 961
Reputation: 77926
Html.BeginForm(
adds a <Form>
tag but I see you are trying to add the form tag inside another form tag as seen below; which is wrong.
<form class="navbar-form navbar-left">
<div class="form-group>
@using (Html.BeginForm("GeneralSearch", "Search",
Again, your controller must expose different action method to cater GET
and POST
request and you should rather have
public ActionResult GeneralSearch()
{
return View();
}
[HttpPost]
public ActionResult GeneralSearch(string searchString)
{
return View("SearchResult", viewModel);
}
Upvotes: 3
Reputation: 9901
You are POSTing to a method that is listening to GET.
Switch the FormMethod
@using (Html.BeginForm("GeneralSearch", "Search", FormMethod.Get))
Upvotes: 1