Search code examples
asp.net-mvcformsasp.net-corerazor

How to pass a selected object to a Controller using Html.DropDownListFor


I'm currently trying to pass a object called DropDown from a View to a controller action using HTML.DropDownFor() and a form.

The object looks like this:

public class DropDown
   {
       public int id { get; set; }

       public string value { get; set; }
   } 

The view Model looks like this:

    public class GraphViewModel
    {
        public DropDown SelectedGraphTypeDropDown { get; set; }
        public IEnumerable<DropDown> GraphTypeDropDowns { get; set; }
    }

The controller action looks like this:

        [HttpPost]
        public string GetTestData(DropDown SelectedGraphTypeDropDown)
        {
            // use above object here
        }

And the view like so:

            @using (Html.BeginForm("GetTestData", "Graph", FormMethod.Post))
            {
                @Html.DropDownListFor(m => m.SelectedGraphTypeDropDown, new SelectList(Model.GraphTypeDropDowns, "id", "value"))
                <input type="submit" />
            }

Rendered HTML

What I expect to happen is the selected GraphType will be passed to the GetTestData action and resolved as a whole object called "SelectedGraphTypeDropDown". I have debugged through it and it seems that the selected GraphType id (int) is passed to the controller but the whole object is not. I have also tried to pass each field of the selectedGraphTypeDropDown but this wont work as the fields are set after the page is rendered.

Also is there a way to pass the full viewModel to the controller?

Any advice would be apricated thanks!


Solution

  • Firstly,dropdown cannot pass a model,but you can add hidden input to bind value.Here is a demo:

    view:

    @using (Html.BeginForm("GetTestData", "Graph", FormMethod.Post))
    {
        @Html.DropDownListFor(m => m.SelectedGraphTypeDropDown.id, new SelectList(Model.GraphTypeDropDowns, "id", "value"))
        <input id="value" name="SelectedGraphTypeDropDown.value" hidden/>
        <input type="submit" />
    }
    

    js(js will bind selected value to hidden input):

    $(function () {
            $("#value").val($(this).find("option:selected").text());
        })
        $("#SelectedGraphTypeDropDown_id").change(function () {
            $("#value").val($(this).find("option:selected").text());
        })
    

    result: enter image description here