public ActionResult Index()
{
return View(db.Employees.Select(x => new { x.First_Name, x.Last_Name,
x.Email }).ToList());
}
There are 5 columns in my table Employee which are First_Name, Last_Name, Address, Salary,Email. Out of these 5 column I want to display only First_Name, Last_Name and Email in Browser.
This is View I am using
@model IEnumerable<crudOperation.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.DisplayNameFor(model => model.First_Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Last_Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
I am getting the error as : An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
I am beginner to asp.net Mvc. How should I proceed ?
db.Employees.ToList()is enough, you're returning anonymous type instead ofEmployeetable property members.EmployeeJust remove your.Select(...)and display only those properties ofEmployeeyou want in the view (but why do you haveDisplayFor()for propertiesAddressandSalaryif you do not want them?)Employeeto the view. you need to create a DTO class with needed properties from theEmployeeand then change the view to@model IEnumerable<YourEmployeeDTO>like this stackoverflow.com/a/46905481/29463291[<>f__AnonymousType43[System.String,System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[crudOperation.Employee]'.1[<>f__AnonymousType43[System.String,System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[crudOperation.Employee]'.]