tags:

views:

293

answers:

2

I am looking for a way to manually add items to html.ListBox in mvc. I want the top item to be "All Items". i.e.

All Items
Item1
Item2
Item3

I am currently calling:

<%=Html.ListBox("items", Model.Items, new { style = "height:50px;width:100%" })%>

I may have to add it in the model when setting up the MultiSelectList, but would be prefer to add this in the controller.

Cheers

A: 

I would prefer doing it in your controller, but for a quick fix I guess you could do something like

<% var items = Model.Items.ToList(); items.Insert(0, new SelectListItem() { Text = "All items" }); %>
<% Html.ListBox("items", items, new { style = "height:50px;width:100%" })%>
Rune
Thanks for the reply Rune. How would you get the correct ordinance at the controller. Simply Adding will only append to the bottom of the bound items?
Chev
Sorted - converted to IList<SelectListItem> and then did and Insert at 0.Thanks
Chev
+1  A: 

You can simply have your view model contain a list of SelectListItem and add the item manually in the controller. For example:

List<SelectListItem> modelSelectList = model.Select(x => new SelectListItem()
                {
                    Text = x.Name,
                    Value = x.ID.ToString()
                }).ToList();

modelSelectList .Add(new SelectListItem() { Selected = false, Text = "All Items", Value = "-1");
Dan
thanks for the reply Dan. Will work but need to position the item at the top of the list
Chev
Sorted - converted to IList<SelectListItem> and then did and Insert at 0. Thanks
Chev