In my MVC 4 site I have a common top menu defined in the _Layout master page. In that menu I have a search input textbox, almost the same as the menu here in stackoverflow site, but I have a submit button apart of the search input text field.
How can I fire an action and submit that form to some controller when I hit that button? Is it possible in MVC?
Here´s the code of the form:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" id="teste" data-provide="typehead" class="form-control" placeholder="Procurar" autocomplete="off">
</div>
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
</form>
Use the MVC razor syntax instead of creating your own forms:
@using(Html.BeginForm("MyAction", "MyController"))
{
<div class="form-group">
<input type="text" id="teste" data-provide="typehead" class="form-control" placeholder="Procurar" autocomplete="off"></div>
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
}
Roger's answer is correct, but I notice your form tag has some HTML attributes, in which case you need to use a different overload of Html.BeginForm()
:
@using (Html.BeginForm("action", "controller",
FormMethod.Post, new { @class = "navbar-form navbar-left", role = "search" }))
{
// ...
}
The @
sign prefixing class
is required, because class
is a keyword in C#. Without it, it will produce an error.
The code above makes the assumption that you are POSTing
your form. If you're using GET
instead, simply change the form method to FormMethod.Get
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With