title: Populate DropDownList in ASP.NET MVC from database table using Entity Framework 6 and ViewModel
body: <p>I have been scratching my head for a whole night on an issue I can do quickly using ajax/jquery and stored procedures. I want to </p>
  
  <p>1) Populate a drop down list from values obtained from a database table using Entity Framework and view model. I DO NOT WANT TO USE VIEWBAG OR VIEWDATA. Any help appreciated.</p>
  
  <p>2) How can I generate a Create View using the View Model with the all the default fields ? The scaffholding works on a model but not on a view model ?</p>
  
  <p><strong>MY MODELS</strong></p>
  
  <pre><code>public class Employee
  {
      public int EmployeeID { get; set; }
      public string Name { get; set; }
      public string Gender { get; set; }
      public string City { get; set; }
      public string Level { get; set; }
      public int DepartmentId { get; set; }
  }
  
  public class Grade
  {
      public int ID { get; set; }
      public string Level { get; set; }
  }
  </code></pre>
  
  <p><strong>View Model</strong></p>
  
  <pre><code>public class GradeSelectListViewModel
  {
  
      public Employee Employee { get; set; }
      public IEnumerable&lt;SelectListItem&gt; Grades { get; set; }
      public GradeSelectListViewModel(Employee employee, IEnumerable grades)
      {
          Employee = employee;
          Grades = new SelectList(grades, "Grade", "Name", employee.Level);
      }
  }
  </code></pre>
  
  <p><strong>MY CONTEXT CLASS</strong></p>
  
  <pre><code>public class EmployeeContext : DbContext
  {
      public DbSet&lt;Employee&gt; Employees { get; set; }
      public DbSet&lt;Department&gt; Departments { get; set; }
      public DbSet&lt;Grade&gt; Grades { get; set; }
  }
  </code></pre>
  
  <p><strong>MY CONTROLLER</strong></p>
  
  <pre><code>public ActionResult Edit (int? id)
  {
      using (var db = new EmployeeContext())
      {
          var model = new GradeSelectListViewModel(db.Employees.Find(id), db.Grades);
          //model.Employee = db.Employees.Single(x =&gt; x.EmployeeID == id);
          model.Grades = db.Grades.ToList().Select(x =&gt; new SelectListItem
          {
              Value = x.ID.ToString(),
              Text = x.Level
          });
          return View(model);
      }
  }
  </code></pre>
  
  <p>MY RAZOR PAGE CSHTML</p>
  
  <pre><code>@model MVCDemo.ViewModels.GradeSelectListViewModel
  ....
  @using (Html.BeginForm()) 
  {
      @Html.AntiForgeryToken()
      ....
      @Html.DropDownListFor(x =&gt; Model.Employee.Level,
          new SelectList(Model.Grades, "ID", "Level"),
          "Select Level")
      ....
      &lt;input type="submit" value="Create" class="btn btn-default" /&gt;
  }
  </code></pre>