将单个列绑定到多选列表

时间:2014-10-01 21:38:15

标签: c# asp.net asp.net-mvc-3

我有一个名为Service的表,其中有一个名为TSBNumber的列。我试图在视图中以多选形式显示值。我对DataText和数据值字段感到困惑,因为这是一个单独的字段,datatext和value字段是相同的。

var tsbNumbersList = (from se in db.ServiceEntry
                                   join r in db.System1 on se.SystemID equals r.ID
                                   where se.Active == true && r.PlatformID == 1 && se.TSBNumber != null
                                   select se.TSBNumber).ToList().Distinct()

我应该直接传入Collection,如果我这样做,那么在视图的下拉列表中我看到System.SelecListItem

   <div class="bodyContent">
            <span class="leftContent"><a id="qTipServiceTsbExportTsbSelection" href=''>
                @Html.Label("TSB Number")</a> </span><span class="rightContent">
                    @Html.ListBoxFor(model => model.SelectedTsbs, new MultiSelectList(ViewBag.TsbNumber, Model.SelectedTsbs),
                    new { id = "Tsblstbox", name = "listbox", @class = "chosen-select", multiple = "multiple", data_placeholder = "Click here to Select Tsb Number...", style = "width:90%;", tabindex = "4" }
                    )
                </span>
        </div>

1 个答案:

答案 0 :(得分:0)

更改查询以删除select子句

var tsbNumbersList = (from se in db.ServiceEntry
  join r in db.System1 on se.SystemID equals r.ID
  where se.Active == true && r.PlatformID == 1 && se.TSBNumber != null
  select se).Distinct();

并根据集合

创建SelectList
ViewBag.TsbNumber = new SelectList(tsbNumbersList, "TSBNumber", "TSBNumber");

并在视图中

 @Html.ListBoxFor(model => model.SelectedTsbs, (SelectList)ViewBag.TsbNumber)

如果string[] SelectedTsbs的值为[“121”,“q231”],则会选择第1和第3个选项。