3

I'm trying to show 2 listboxes one with all the possible choices & other will populate as users select their choices but for some reason I can't add an empty listbox.

Here is the code:

@Html.ListBox("somename")

& my error is: There is no ViewData item of type 'IEnumerable' that has the key 'somename'.

It I replace the above line of code with the following then it works fine but I want an empty listbox:

@Html.ListBox("somename", liMyList)

where liMyList is SelectListItem.

is it possible to have an empty listbox in MVC? Please help

4

2 回答 2

8

一种选择是纯 HTML:

<select name="somename" multiple="multiple">
</select>

另一种是提供一个空的项目列表:

@Html.ListBox("somename", new List<SelectListItem>())
于 2013-06-17T14:42:19.253 回答
0

我意识到这是一个较老的问题,但我解决这个问题的方法是在我的视图模型中有 2 个 IEnumerable 成员(我的模型使用 List<>)。第一个成员是可供选择的列表,第二个成员是选择的接收者,两个框之间的按钮用于管理移动所选项目。

public class DataViewModel
{
    // some other model members
    public List<SelectListItem> SourceList { get; set; }
    public List<SelectListItem> DestinationList { get; set; }
}

在我的控制器中,我只是为两个成员创建了新列表

DataViewModel vm = new DataviewModel() {
    SourceList = new List<SelectListItem>(),
    DestinationList= new List<SelectListItem>(),
    // Other initialization
}

然后,我将从我正在使用的任何源中填充源列表(在我的应用程序中,我从 Active Directory 中检索用户列表)。如果您的应用程序允许显示当前选择以删除它们或仅显示它们,您还可以填充目标列表。但填充列表不是强制性的。

然后,在我看来,我只是添加了具有适当绑定的两个列表:

@model Application.WebApp.Models.DataViewModel
<!-- Some HTML/Razor Markup -->
<div class="form-group">
    <div class="col-sm-3">
        @Html.ListBoxFor(m => m.SourceList, Model.SourceList, new {size = 10})
    </div>
    <div class="col-sm-1">
        <input type="submit" class="btn" value="--&gt;&gt;" name="Action"/>
        <input type="submit" class="btn" value="--&gt;" name="Action"/>
        <input type="submit" class="btn" value="&lt;--" name="Action"/>
        <input type="submit" class="btn" value="&lt;&lt;--" name="Action"/>
    </div>
    <div class="col-sm-3">
        @Html.ListBoxFor(m => m.DestinationList, Model.DestinationList, new {size = 10})
    </div>
</div>
<!-- Some HTML/Razor Markup -->

对于视图,您可能需要使用标记来满足您的目的。

于 2017-01-04T14:35:12.560 回答