从下拉列表数组中获取选定的项目

时间:2019-02-20 21:31:49

标签: asp.net-mvc

我有很多下拉列表,它们是动态创建的? Му模型:

public class Block
{
    public string SelectedField { get; set; }
}

public class Form
{
      ......
      public List<Block> Blocks { get; set; }

      public List<SelectListItem> Fields { get; set; } = new List<SelectListItem>()
      {
            new SelectListItem { Value = "1", Text = "text1"},
            new SelectListItem { Value = "2", Text = "text2" },
            new SelectListItem { Value = "3", Text = "text3" },
            new SelectListItem { Value = "4", Text = "text4"},
            new SelectListItem { Value = "5", Text = "text5" }
       };
}

我如何从视图中获取选定的项目?

@model FormEditor.Models.Form
.......
  @for (int i = 0; i < Model.Blocks.Count; i++)
  {
        @Html.DropDownListFor(x => x.Blocks[i].SelectedField, new SelectList(Model.Fields,"Value","Text"), new { @class= "custom-select" })

此代码返回null

1 个答案:

答案 0 :(得分:0)

首先如下更新您的Block类:

public class Block
{
    public List<string> SelectedField { get; set; }
}

然后按如下所示操作您的@Html.DropDownListFor

@Html.DropDownListFor(x => x.Blocks[i].SelectedField, Model.Fields,"Select Item" new { @class= "custom-select" })