Question

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

Was it helpful?

Solution

One option is just a pure HTML:

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

Another is to supply an empty list of items:

@Html.ListBox("somename", new List<SelectListItem>())

OTHER TIPS

I realize this is an older question, but the way I got around this was to have 2 IEnumerable members in my view model (my model used List<>). The first member was the list to choose from, and the second would be the recipient of the choices, with buttons between the 2 boxes to manage moving the selected items.

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

In my controller, I simply created new lists for both members

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

I would then populate the Source List from whatever source I was using (In my application I was retrieving a list of users from Active Directory). You can also populate the destination list if your application allows for displaying current choices in order to remove them, or just to display them. But populating the list is not mandatory.

Then, in my view, I just added both lists with the appropriate binding:

@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 -->

For the view, you will probably need to play with the markup to suit your purposes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top