Geeks With Blogs
TFS Austin Agile SCM Talk Visual Studio ALM Team Foundation Server Practice


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

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:


//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();

//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;" })

Posted on Tuesday, December 18, 2012 11:09 AM | Back to top

Comments on this post: MVC4 Razor @Html.DropDownList with Entity Framework Code First

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Bob Hardister | Powered by: | Join free