Blog Stats
  • Posts - 61
  • Articles - 0
  • Comments - 6
  • Trackbacks - 0

 

Tuesday, December 18, 2012

MVC4 Razor @Html.DropDownList with Entity Framework Code First


Controller

ViewData["Projects"] = new SelectList(db.Projects.Select(r => r.ProjectName));
View
@Html.DropDownList("Projects")

There were many complicated examples, but this worked for me. However, I needed to pull from a database and manipulate the data before populating the dropdown. Here’s what I ended up with:

Controller

//retrieve the list of projects from the projects table
var ProjectQry = (from p in db.Projects orderby p.Project_Name
             select new { projectName = p.Project_Name, ID = p.ID }).ToList();

//format project name and ID into single field
var projectList = from p in ProjectQry 
             select new { project = p.projectName + " (" + p.ID + ")" };
            

//send the list and return
ViewData["selection"] = new SelectList(dropdownList.Select(i => i.project), blankLine);
return View();
View

//formats and inserts a blank line as the default in the list @Html.DropDownList(

"selection", null, string.Empty,

new { style = "font-size: .85em; font-weight: normal;" })

 

 

Copyright © Bob Hardister