Bilal Ahmed
Bilal Ahmed

Reputation: 1129

The model item passed into the dictionary is of type List, but this dictionary requires a model item of type IEnumerable

I'm facing an exception below :

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DropDownList.Models.Department]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[DropDownList.Models.Employee]'.

Here is my model, Employee.cs :

public class Employee
{
    public int EmployeeId { get; set; }  
    public string EmployeeName { get; set; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
}

Department.cs :

public class Department
{
    public int DepartmentId { get; set; }
    public string DeptCode { get; set; }
    public string DepartmentName { get; set;}
    public string Syscode { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

and my EmployeesController's index action, where the exception generates :

public ActionResult Index()
{
var employees =
            from dept in db.Departments
            select new
            {
                dept,
                depts = from emp in dept.Employees
                        where dept.Syscode == "isols123"
                        select dept
            };
        var employs = employees
            .AsEnumerable()
           .Select(m => m.dept);
        return View(employs.ToList());
}

and here is my index view :

@model IEnumerable<DropDownList.Models.Employee>
.
.
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Department.DepartmentName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.EmployeeName)
    </td>
</tr>
}

What is going wrong, I've no idea, I'm seriously stuck on this one :(, anyone please take me out of this, Thanks in Advance..

Upvotes: 0

Views: 94

Answers (1)

NikolaiDante
NikolaiDante

Reputation: 18649

Essentially, the code:

public ActionResult Index()
{
var employees =
            from dept in db.Departments // This makes dept of type Department
            select new
            {
                dept,
                depts = from emp in dept.Employees
                        where dept.Syscode == "isols123"
                        select dept
            };
        var employs = employees
            .AsEnumerable()
           .Select(m => m.dept); // Selects Department
        return View(employs.ToList());
}

Returns a list of Departments (even tho the variables are called employs) and your view expects it to be a list of Employees.

Both these should match for it to work.

Assuming the linq queries are right, this will make it expect a List of Departments on the view:

@model List<DropDownList.Models.Department>

Upvotes: 1

Related Questions