Asp.net-mvc – ASP.net MVC Listbox

asp.net-mvc

I have a number of Html.Listbox controls on my view which are being populated by an IEnumberable<SelectListItem>

Is there a way that when the data is populated, that some items are automatically selected?

The particular selectlist items in the IEnumerable are marked as Selected = true, yet this does not convey into the view.

The view is as such:

<%= Html.ListBox("projects", Model.Projects)%>

Thanks.

Best Answer

Sure as always you start by defining a view model that will represent the information you would like to show on the particular view:

public class MyViewModel
{
    public string[] SelectedItems { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SelectedItems = new[] { "1", "3" },
            Items = new[] 
            {
                new SelectListItem { Value = "1", Text = "Item 1" },
                new SelectListItem { Value = "2", Text = "Item 2" },
                new SelectListItem { Value = "3", Text = "Item 3" },
            }
        };
        return View(model);
    }
}

and finally in your strongly typed view:

<%= Html.ListBoxFor(
    x => x.SelectedItems, 
    new SelectList(Model.Items, "Value", "Text")
) %>

As expected Item 1 and Item 3 will be preselected when the list box is rendered.