TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Sabab Zulfiker
NA
85
25.6k
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]'.
Reply
Answers (
1
)
Execute other stored procedures from C#
AJAX based polling in ASP.NET MVC application