3

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.

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent that works as expected. When I query this approach with my boss, and indeed what I had done before, he says that the MVC model should be stateless and that we should not keep track of data such as this. Instead it should just pass data between View and Model and deal with what is passed only. Is that correct? 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.