如何接收在后端代码中选择的下拉列表值

时间:2017-07-06 16:34:26

标签: c# asp.net asp.net-mvc drop-down-menu asp.net-mvc-5

我是网络开发和学习Dropdown HTML Helper的新手。所以,我创建了下拉列表,但我无法在后端接收选定的值。

以下是我的尝试。

查看:

@model WebApplication3.Models.DropDownViewModel
<form method="post">
    @Html.DropDownListFor(m => m.SongList, new SelectList(Model.SongList, "Value", "Text"), "Select menu", new { @class = "form-control" })
            @* below is the use of each argument.*@
            @*1. m=>m.SongList => It helps in strongly typing to the model*@
            @*2. Model.SongList => It is the datasource for creating the dropdown*@
            @*3. "Value" => This is the value behind each of the dropdown options*@
            @*4. "Text" => This is the actual text*@
            @*5. "Select Menu" => This is the first option that will appear in the dropdown*@
                <input type="submit" value="Send" />
            </form>

型号:

                public class DropDownViewModel
                {
                    public DropDownViewModel()
                    {
                        SongList = new List<SelectListItem>();
                    }
                    public int Id { get; set; }
                    public List<SelectListItem> SongList { get; set; }
                }

控制器:

                 public ActionResult Index()
                    {
                        DropDownViewModel dropdown = new DropDownViewModel();
                        dropdown.SongList.Add(new SelectListItem { Text = "Four", Value = "4" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Five", Value = "5" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Six", Value = "6" });
                        dropdown.SongList.Add(new SelectListItem { Text = "Seven", Value = "7" });

                        return View(dropdown);
                    }

                    [HttpPost]
                    public ActionResult Index(DropDownViewModel viewModel)
                    {
                    *******  viewModel.??? WHow to get the selected ID. Which variable will have that.*******
                        return View(dropdown);
                    }

1 个答案:

答案 0 :(得分:2)

您需要在DropDownViewModel中添加一个属性来检索所选的值。

apply

视图

    public class DropDownViewModel
    {
       public DropDownViewModel()
       {
          SongList = new List<SelectListItem>();
       }
       public int Id { get; set; }

       public string SelectedSongId { get; set; }
       public List<SelectListItem> SongList { get; set; }
    }

行动方法

@using (Html.BeginForm()) 
{  
   @Html.DropDownListFor(model => model.SelectedSongId, Model.SongList, new { @class = "form-control" })
   <button type="submit" value="Submit" class="btn btn-primary">Submit</button>
}