我有以下Action方法,它有一个带有字符串列表的viewBag: -
public ActionResult Login(string returnUrl) { Listdomains = new List (); domains.Add("DomainA"); ViewBag.ReturnUrl = returnUrl; ViewBag.Domains = domains; return View(); }
在视图上我试图建立一个下拉列表,显示viewBag字符串如下: -
@Html.DropDownList("domains",(SelectList)ViewBag.domains )
但我得到以下错误: -
无法将类型'System.Collections.Generic.List'转换为'System.Web.Mvc.SelectList'
那么有人可以为什么我不能填充我的DropDown列表中的蜇伤列表?谢谢
因为DropDownList
不接受字符串列表.它接受IEnumerable<SelectListItem>
.您有责任将您的字符串列表转换为该字符串.这很容易:
domains.Select(m => new SelectListItem { Text = m, Value = m })
然后,您可以将其提供给DropDownList
:
@Html.DropDownList("domains", ((List<string>)ViewBag.domains).Select(m => new SelectListItem { Text = m, Value = m }))