Reputation: 16851
I am getting the following error.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MYAPP.Models.User]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MYAPP.Models.ViewModel.AccountViewModel]'.
My code is as follows:
VIEWMODEL
public class AccountViewModel
{
...
public IQueryable<User> user { get; set; }
}
CONTROLLER
public class UserController : Controller
{
private REc db = new REc();
// GET: /User/
public ActionResult Index()
{
AccountViewModel avm = new AccountViewModel();
var users = db.Users.Include(u => u.USERROLE);
avm.user = users;
return View((avm.user).ToList());
}
VIEW
@model IEnumerable<SNAPAPP.Models.ViewModel.AccountViewModel>
@{
ViewBag.Title = "Index";
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.USERROLE)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.USERROLE)
</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>
Upvotes: 0
Views: 1007
Reputation: 295
in your controller, use this to return the model to the view
return View(avm.user.AsEnumerable);
your db query returns a IQueryable, you did put the ToList on the whole model, not on the user field
Upvotes: 0
Reputation: 218732
Your razor view is strongly typed to a collection of AccountViewModel
class objects. But your current action method code is sending a list of User
entity (the entity class which is totally different than your view model class). That is the reason you are getting this type mismatch error.
You should send the correct type from your action method. You may use projection on your linq statement to get a collection of AccountViewModel from the db.Users
collection.
var accountViewModelList = db.Users
.Select(x=> new AccountViewModel { Id=x.Id })
.ToList();
return View(accountViewModelList);
The above code will basically create a list of AccountViewModel
objects and read each User entity object's Id
property value and assign it to the corresponding view model object's Id
property. If you want more properties in your view, you should map those as well.
For example, if you have a FirstName property in both your entity class and view model, you may do this,
var accountViewModelList = db.Users
.Select(x=> new AccountViewModel {
Id=x.Id,
FirstName = x.FirstName })
.ToList();
Upvotes: 2