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

 周佳君7284 发布于 2023-01-30 12:37

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

public ActionResult Login(string returnUrl)
        {
            List domains = 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列表中的蜇伤列表?谢谢

1 个回答
  • 因为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 }))
    

    2023-01-30 12:40 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有