Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a form from layout page in MVC?

Tags:

c#

asp.net-mvc

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>
like image 337
gog Avatar asked Oct 20 '25 01:10

gog


2 Answers

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>
}
like image 54
Roger Far Avatar answered Oct 22 '25 17:10

Roger Far


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.

like image 36
John H Avatar answered Oct 22 '25 15:10

John H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!