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
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 }))
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With