Question

In aspx file I have: = Html.DropDownList("SiteID", ViewData["Sites"] as SelectList)

In cs file I have:

ViewData["Sites"] = new SelectList(pr.GetUnassignedPortfolioSites(GetAuthenticatedContext(), id), "SiteID", "SiteName");

It works, however, I need to sort the SelectList so it is nicely sorted when the dropdown menu is selected.

Also, I would need to select one item from the list, and make it appear a first item visible before the dropdown menu is clicked.

Thank you very much for your help!

PS I have tried looking trough other examples, but no luck.

Was it helpful?

Solution

I've changed it a little bit, looks like SelectList has some issues to set the default selected item.

Look at this:

@{
  List<SelectListItem> list = (List<SelectListItem>)ViewData["Sites"];
  list.Where(x => x.Value == "1").Single().Selected = true;
}
@Html.DropDownList("SiteID", list.OrderBy(x => x.Selected).ThenBy(x => x.Text))

And the controller:

        List<SelectListItem> items = new List<SelectListItem>();

        items.Add(new SelectListItem { Text = "Action", Value = "0" });

        items.Add(new SelectListItem { Text = "Drama", Value = "1" });

        items.Add(new SelectListItem { Text = "Comedy", Value = "2" });

        items.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });

        ViewData["Sites"] = items;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top