I am trying to pass a list of Objects from controller to View ,where the attributes of the objects are retrieved from database using LINQ. The MODEL Code is given below:
public class Department
{
[Key]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "Enter Department Name")]
[DisplayName("Department Name")]
public string DepartmentName { get; set; }
}
The Controller Code is :
public ActionResult ShowDepartments()
{
var departmentList = db.Deapartment.Select(x => new
{
x.DepartmentId,
x.DepartmentName
}).ToList();
return View(departmentList);
}
And the View Code is:
@model List
@{
ViewBag.Title = "ShowDepartments";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Show Departments
@department.DepartmentId | @department.DepartmentName |
}
But when I run the project, it shows the following exception:
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType3`2[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[PractiseMVC11_17_2017.Models.Department]'.

Nilesh ShahPosted Nov 16, 2017, 4:35 PM