如何使用 Html.DropDownListFor 将选定对象传递给控制器

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

我目前正在尝试使用 HTML.DropDownFor() 和表单将名为 DropDown 的对象从视图传递到控制器操作。

对象看起来像这样:

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

       public string value { get; set; }
   } 

视图模型如下所示:

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

控制器动作如下所示:

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

这样的视图:

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

Rendered HTML

我希望发生的是选定的 GraphType 将传递给 GetTestData 操作并解析为一个名为“SelectedGraphTypeDropDown”的整个对象。 我已经通过它进行了调试,似乎所选的 GraphType id (int) 已传递给控制器​​,但整个对象并未传递。我还尝试传递 selectedGraphTypeDropDown 的每个字段,但这不会起作用,因为这些字段是在页面呈现后设置的。

还有没有办法将完整的 viewModel 传递给控制器​​?

如有任何建议,将不胜感激!

首先,dropdown不能传递模型,但是你可以添加隐藏输入来绑定value.Here是一个演示:

查看:

@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 会将选定的值绑定到隐藏的输入):

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

结果: