How to fill dropdownlist for MVC4 razor views (C#)

2019-02-20 18:31发布

问题:

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

回答1:

Add a SelectList to your ViewBag in the Controller:

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.