asp.net-mvc 如何为 MVC4 razor 视图填充下拉列表 (C#)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17574290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:00:52 来源:igfitidea点击:
How to fill dropdownlist for MVC4 razor views (C#)
提问by Pakk
UserProfiles Model
用户配置文件模型
[Table("Users")]
public class UserProfiles
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
//public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Initials { get; set; }
public string Company { get; set; }
public string Department { get; set; }
public string Title { get; set; }
public string Team { get; set; }
public string TeamSub { get; set; }
public string Phone { get; set; }
public string ImageLocation { get; set; }
public string Note { get; set; }
public string Comment { get; set; }
}
Controller
控制器
public ActionResult Index()
{
**EDIT :** ViewBag.ProfileId = new SelectList(db.UserProfiles, "UserName", "UserName");
return View(db.UserProfiles.ToList());
}
In the View ( i hope / believe here is the issue )
在视图中(我希望/相信这是问题所在)
@model IEnumerable<OilNGasWeb.Models.UserProfiles>
@{
ViewBag.Title = "CLS - Oil & Gas Web Site Users";
}
<h2>Web Site Users</h2>
**Removed** @Html.DropDownList(Model => Model.UserName,Model.UserName)
**Changedinto** @Html.DropDownList("UserName", String.Empty)
New Error:
新错误:
Exception Details: System.InvalidOperationException: There is no ViewData item of
type 'IEnumerable<SelectListItem>' that has the key 'UserName'.
回答by glautrou
Add a SelectList to your ViewBagin the Controller:
ViewBag在控制器中添加一个 SelectList :
ViewBag.ProfileId = new SelectList(db.UserProfiles, "Id", "Username");
then add this in your View:
然后在你的视图中添加这个:
@Html.DropDownList("ProfileId", String.Empty)
Moreover you should have used "model" instead of "Model" in your lambda expression.
此外,您应该在 lambda 表达式中使用“模型”而不是“模型”。

