如何填写MVC4剃刀视图的下拉列表(C#)

时间:2013-07-10 15:09:37

标签: asp.net-mvc razor html-select

UserProfiles模型

[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; }

}

控制器

     public ActionResult Index()
    {
        **EDIT :** ViewBag.ProfileId = new SelectList(db.UserProfiles, "UserName", "UserName");
        return View(db.UserProfiles.ToList());
    }

在视图中(我希望/相信这是问题)

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

新错误:

Exception Details: System.InvalidOperationException: There is no ViewData item of 
type 'IEnumerable<SelectListItem>' that has the key 'UserName'.

1 个答案:

答案 0 :(得分:6)

将SelectList添加到Controller中的ViewBag

ViewBag.ProfileId = new SelectList(db.UserProfiles, "Id", "Username");

然后在您的视图中添加:

@Html.DropDownList("ProfileId", String.Empty)

此外,您应该在lambda表达式中使用“model”而不是“Model”。