无法将类型'System.Collections.Generic.List <string>'转换为'System.Web.Mvc.SelectList'

joh*_* Gu 15 asp.net-mvc html-helper asp.net-mvc-4

我有以下Action方法,它有一个带有字符串列表的viewBag: -

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

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.Domains = domains;
            return View();
        }
Run Code Online (Sandbox Code Playgroud)

在视图上我试图建立一个下拉列表,显示viewBag字符串如下: -

@Html.DropDownList("domains",(SelectList)ViewBag.domains )
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误: -

无法将类型'System.Collections.Generic.List'转换为'System.Web.Mvc.SelectList'

那么有人可以为什么我不能填充我的DropDown列表中的蜇伤列表?谢谢

Chr*_*att 29

因为DropDownList接受字符串列表.它接受IEnumerable<SelectListItem>.您有责任将您的字符串列表转换为该字符串.这很容易:

domains.Select(m => new SelectListItem { Text = m, Value = m })
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其提供给DropDownList:

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


dom*_*dom 5

要完成 Chris Pratt 的回答,以下是一些用于创建下拉菜单的示例代码:

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

这将产生以下标记:

<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>
Run Code Online (Sandbox Code Playgroud)