1

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

1
  • Can you post some of the controller's code ? Commented Feb 22, 2010 at 16:48

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply Dan. Will work but need to position the item at the top of the list
Sorted - converted to IList<SelectListItem> and then did and Insert at 0. Thanks
1

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%" })%>

2 Comments

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?
Sorted - converted to IList<SelectListItem> and then did and Insert at 0. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.