I’m new to using both Entity Framework and MVC, but not new to programming. I am working with a large table and I want to return selected columns of the query back to the view and list them. The basic query is as follows:
public class EmployeeController : Controller
{
private ADPEntities db = new ADPEntities();
// GET: /Employee/
public ActionResult Index()
{
var tblEmployeeADPs = db.tblEmployeeADPs
.Where(p => p.Status == "Active")
.Select(p => new UserViewModel.USerViewModelADP
{
Status = p.Status,
FirstName = p.FirstName,
LastName = p.LastName,
SSN = p.SSN
});
return View(tblEmployeeADPs.ToList());
}
}
I created a basic C# class to strongly type the results (i.e. UserViewModel
) and I still get an error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[UserViewModel.USerViewModelADP]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[DysonADPTest.Models.tblEmployeeADP]'.
when I execute the page.
I’m not sure what I’m missing, as I was sure that (cobbling what I’ve read) that this would be the answer.
Please try the following in your view:
@model IEnumerable<DysonADPTest.UserViewModel.USerViewModelADP>
Your problem lies in using the .Select() method which changes the type your controller action is returning from
IEnumerable<DysonADPTest.Models.tblEmployeeADP>
which your view is also expecting to something entirely different. For this to work, the type your controller action returns and your view uses should match. It's either not use the .Select() method in your controller action or change the type your view uses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With