简体   繁体   中英

Binding Drop Down list in asp.net mvc

I am binding my drop down list with database using EF code first approach.My model class is department

  public class Department
{
    [Key]
    public int DepartmentID { get; set; }
    [Required]

    [Display(Name = "Department")]

    public string DepartmentName { get; set; }

}

I am getting all department name in ViewData

 ViewData["Departments"] = new SelectList(db.Departments,"DepartmentName");

In my view my code is this

@Html.DropDownList("Departments", "Select Department")

Thid code binding my data but not with name but their are 10 objects like MyProjectName.Models.Department

MyProjectName.Models.Department

MyProjectName.Models.Department

MyProjectName.Models.Department

MyProjectName.Models.Department ....

Need help what is going wrong in my code.

Try using the correct constructor of the SelectList class taking the collection, the value and text property:

ViewData["Departments"] = new SelectList(db.Departments, "DepartmentID", "DepartmentName");

You might also consider using view models and get rid of the weakly typed ViewData. So, start by defining your view model:

public class MyViewModel
{
    public int SelectedDepartmentID { get; set; }
    public IEnumerable<SelectListItem> Departments { get; set; }
}

that your controller action will populate and pass to the view:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.Departments = db.Departments.ToList().Select(d => new SelectListItem
    {
        Value = d.DepartmentID.ToString(),
        Text = d.DepartmentName,
    });
    return View(model);
}

and in your strongly typed view you could use the strongly typed DropDownListFor version of the helper to generate the dropdown:

@model MyViewModel
...
@Html.DropDownListFor(x => x.SelectedDepartmentID, Model.Departments, "Select Department")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM