1

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'.
4

1 回答 1

5

ViewBag在控制器中添加一个 SelectList :

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

然后将其添加到您的视图中:

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

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

于 2013-07-10T15:18:44.180 回答