I get the error,

Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'DepartmentID'

for the following code in asp.net mvc using linq object.

(only the necessary part was taken from the entire codes)

Your help is greatly appreciated. Thanks!

Database :two tables

(1)departments: int d_id (primary key), string d_name

(2)staffs: int staff_id(primary key), int staff_departmentId(foreign key reference [departments] d_id)

Model:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;

 namespace d.Models
 {

  directoryLinqDataContext objDirectory = new directoryLinqDataContext();

  public IQueryable<department> getDepartments()    
  {
   var allDepartments = objDirectory.departments.Select(x => x);
   return allDepartments;    
  }

 public IQueryable<staff> getStaff()
 {
   var allStaff = objDirectory.staffs.Select(x => x);
   return allStaff;
 }

 public bool commitInsertS(staff s)
 {
   using (objDirectory)
   {
     objDirectory.staffs.InsertOnSubmit(s);
     objDirectory.SubmitChanges();
     return true;
   }
 }
}

Controller:

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 => 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 => new { d.d_id, d.d_name });

  ViewBag.DepartmentID = new SelectList(q.AsEnumerable(), "d_id", "d_name", s.staff_departmentId);

  return View();
}

View:

@model d.Models.staff
@using (Html.BeginForm())
{
    @Html.ValidationSummary();
    @Html.DropDownList("DepartmentID")
   <input type="submit" value="Insert New Staff" />
 }
@section Scripts{
  @Scripts.Render("~/bundles/jqueryval")
 }

Related posts

Recent Viewed