Sabab Zulfiker

Sabab Zulfiker

  • NA
  • 85
  • 24.7k

Passing list of Objects from Controller to View

Nov 16 2017 4:01 PM
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<PractiseMVC11_17_2017.Models.Department>
@{
ViewBag.Title = "ShowDepartments";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Show Departments</h2>
<div>
<table class="table table-bordered table-hover">
<tbody>
@foreach (var department in Model)
{
<tr>
<td>
@department.DepartmentId
</td>
<td>
@department.DepartmentName
</td>
</tr>
}
</tbody>
</table>
</div>
}
 
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]'.

Answers (1)