MVC DropDownList:将List转换为SelectListItem

时间:2016-10-18 10:54:28

标签: asp.net-mvc drop-down-menu selectlistitem

我有一个控制器

 public class HomeController : Controller
    {         
        // GET: Home
        public ActionResult Index()
        {
            ViewData["Users"] = DataFill.GetUsers();
            return View();
        }
    }

查看:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
<div>
    @Html.DropDownList("Numbers",(IEnumerable<SelectListItem>)ViewData["UserList"])
</div>
</body>
</html>

型号:

public class User
{
    public string DisplayName { get; set; }
    public string Login { get; set; }
}

填充列表的方法:

public static List<SelectListItem> GetUsers()
{
    using (var command = new SqlCommand(query, DbConnection))
    {
        DbConnection.Open();
        using (var reader = command.ExecuteReader())
        {

            while (reader.Read())
                UserList.Add(new User {Login = reader.GetString(0), DisplayName = reader.GetString(1)});
        }
    }

    return UserList.ToList();
}

但在Visual Studio中我收到错误: “无法将表达式类型User转换为返回类型SelectListItem”。那么如何将我从数据库中获取的列表转换为SelectListItem类型?

1 个答案:

答案 0 :(得分:0)

以下是将List转换为SelectListItem的解决方案:

public static List<SelectListItem> GetUsers() 
{
    List<SelectListItem> items = new List<SelectListItem>();
    using (var command = new SqlCommand(query, DbConnection)) 
    {
        DbConnection.Open();
        using (var reader = command.ExecuteReader()) 
        {
            while (reader.Read()) 
            {
                items.Add(new SelectListItem { 
                Text = reader.GetString(0), 
                Value = reader.GetString(1)
                });
            }
        }
    }
    return items;
}