title: How to insert a field(foreign key) using dropdownlist in asp.net - Basic MVC4.0?
body: <p>I get the error,</p>
  
  <p><strong>Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'DepartmentID'</strong> </p>
  
  <p>for the following code in asp.net mvc using linq object.</p>
  
  <p>(only the necessary part was taken from the entire codes)</p>
  
  <p>Your help is greatly appreciated. Thanks!</p>
  
  <p><strong>Database</strong> :two tables</p>
  
  <p>(1)departments: int d_id (primary key), string d_name</p>
  
  <p>(2)staffs: int staff_id(primary key), int staff_departmentId(foreign key reference [departments] d_id) </p>
  
  <p><strong>Model</strong>:</p>
  
  <pre><code> using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Web;
  
   namespace d.Models
   {
  
    directoryLinqDataContext objDirectory = new directoryLinqDataContext();
  
    public IQueryable&lt;department&gt; getDepartments()    
    {
     var allDepartments = objDirectory.departments.Select(x =&gt; x);
     return allDepartments;    
    }
  
   public IQueryable&lt;staff&gt; getStaff()
   {
     var allStaff = objDirectory.staffs.Select(x =&gt; x);
     return allStaff;
   }
  
   public bool commitInsertS(staff s)
   {
     using (objDirectory)
     {
       objDirectory.staffs.InsertOnSubmit(s);
       objDirectory.SubmitChanges();
       return true;
     }
   }
  }
  </code></pre>
  
  <p><strong>Controller</strong>:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  
  using d.Models;
  
  namespace d.Controllers
  {
  public class DirController : Controller
  {
  
   public ActionResult staffInsert()
   {
     var q = objDir.getDepartments().Select(d =&gt; new { d.d_id, d.d_name });            
     ViewBag.DepartmentID = new SelectList(q, "d_id", "d_name", null);
  
     return View();
   }
  
  
  [HttpPost]
  public ActionResult staffInsert(staff s)
  {
    if (ModelState.IsValid)
      {
       try
       {                    
         objDir.commitInsertS(s);
         return RedirectToAction("Index");
       }
       catch
       {
         return View();
       }
    }
  
    var q = objDir.getDepartments().Select(d =&gt; new { d.d_id, d.d_name });
  
    ViewBag.DepartmentID = new SelectList(q.AsEnumerable(), "d_id", "d_name", s.staff_departmentId);
  
    return View();
  }
  </code></pre>
  
  <p><strong>View</strong>:</p>
  
  <pre><code>@model d.Models.staff
  @using (Html.BeginForm())
  {
      @Html.ValidationSummary();
      @Html.DropDownList("DepartmentID")
     &lt;input type="submit" value="Insert New Staff" /&gt;
   }
  @section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
   }
  </code></pre>