Search code examples
asp.net-mvcasp.net-mvc-4html-helper

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


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


Solution

  • 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 }))