本文介绍了无法转换类型'System.Collections.Generic.List< string>'到'System.Web.Mvc.SelectList'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();
        }

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

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 :-

所以有人能容忍为什么我不能填充st的下拉列表吗?谢谢

So can anyone adive why i can not populate my DropDown list of a list of stings ?Thanks

推荐答案

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

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 })

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

Then, you can feed that to DropDownList:

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

这篇关于无法转换类型'System.Collections.Generic.List&lt; string&gt;'到'System.Web.Mvc.SelectList'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:31