Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 285
john Gu Avatar asked Jan 30 '14 17:01

john Gu


2 Answers

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 }))
like image 196
Chris Pratt Avatar answered Oct 26 '22 22:10

Chris Pratt


To complete Chris Pratt's answer, here's some sample code to create the dropdown :

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

Which will produce the following markup :

<select id="domains" name="domains">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
</select>
like image 41
dom Avatar answered Oct 26 '22 22:10

dom