Cannot convert type 'System.Collections.Generic.List<string>' to 'System.Web.Mvc.SelectList'

john Gu picture john Gu · Jan 30, 2014 · Viewed 52.2k times · Source

I have the following Action method, which have a viewBag with a list of strings:-

public ActionResult Login(string returnUrl)
        {
            List<string> domains = new List<string>();
    domains.Add("DomainA");

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.Domains = domains;
            return View();
        }

and on the view i am trying to build a drop-down list that shows the viewBag strings as follow:-

@Html.DropDownList("domains",(SelectList)ViewBag.domains )

But i got the following error :-

Cannot convert type 'System.Collections.Generic.List' to 'System.Web.Mvc.SelectList'

So can anyone adive why i can not populate my DropDown list of a list of stings ? Thanks

Answer

Chris Pratt picture Chris Pratt · Jan 30, 2014

Because DropDownList does not accept a list of strings. It accepts IEnumerable<SelectListItem>. It's your responsibility to convert your list of strings into that. This is easy enough though:

domains.Select(m => new SelectListItem { Text = m, Value = m })

Then, you can feed that to DropDownList:

@Html.DropDownList("domains", ((List<string>)ViewBag.domains).Select(m => new SelectListItem { Text = m, Value = m }))