How to send data from view to controller on button click

11,710

Solution 1

In order for the data to be submitted to the controller, the inputs must appear within the <form> tag.

For example:

<body>
    <div>
        @using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post))
        {

            @Html.DropDownList("Name")
            <br />
            @Html.DropDownList("Age")
            <br />
            @Html.DropDownList("Gender")
            <br />
            <input type="submit" value="Find" />
        }
    </div>
</body>

Solution 2

inside the @using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post)) you should put your inputs.

You have your inputs outside the Form

@using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post))
    {
    @Html.DropDownList("Name")
    <br />
    @Html.DropDownList("Age")
    <br />
    @Html.DropDownList("Gender")
    <br />

        <input type="submit" value="Find" />
}

Solution 3

First u need the Model to bind your data.

 public class TestModel
    {
        public string Age { get; set; }
        public string Gender { get; set; } 
        ...
    }

then you need to wrap your dropLists in form tag

<form method='post'>
 @Html.DropDownList("Age")
</form>

and action to recive posted data

 [HttpPost]
        public ActionResult YourAction(TestModel model)//selected data here
        {

        }
Share:
11,710
watbywbarif
Author by

watbywbarif

SOreadytohelp

Updated on June 05, 2022

Comments

  • watbywbarif
    watbywbarif almost 2 years

    How can I invoke controller action and send which values are selected in drop down lists in time when button was clicked? Here is example how my .cshtml looks like. This is just example, generally I need to collect much data from current view in time when button was clicked.

    <body>
        <div>
            @Html.DropDownList("Name")
            <br />
            @Html.DropDownList("Age")
            <br />
            @Html.DropDownList("Gender")
            <br />
            @using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post))
            {
                <input type="submit" value="Find" />
            }
        </div>
    </body>
    
  • watbywbarif
    watbywbarif almost 11 years
    Thx. To help someone else how to use this in controller: public ActionResult FindPerson(FormCollection form)