Reputation: 27
I'm trying to list all my Users, but I'm getting the following error:
'IEnumerable<>' does not contain a definition for 'UsersVm' and no extension method 'UserVm' accepting a first argument of type 'IEnumerable' could be found
My Code is as follow:
Model:
public class UserEntity
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual string PasswordHash { get; set; }
}
ViewModel:
public class UsersIndex
{
public IEnumerable<UserEntity> UsersVm { get; set; }
}
View (I get the error here at '.UsersVm
')
@model IEnumerable<MyBlog.Areas.Admin.ViewModels.UsersIndex>
<h1>Admin Users</h1>
<ul>
@foreach (var user in Model.UsersVm)
{
<li>@user.Username</li>
}
</ul>
Controller:
public class UsersController : Controller
{
MyBlogEntities db = new MyBlogEntities();
// GET: Admin/Users
public ActionResult Index()
{
var users = db.Users.ToList();
return View(users);
}
}
MyBlogEntities (DbContext)
public class MyBlogEntities : DbContext
{
public DbSet<UserEntity> Users { get; set; }
}
Upvotes: 0
Views: 2608
Reputation: 24270
Class UsersIndex is not needed, and then the View becomes this:
@model IEnumerable<MyBlog.Areas.Admin.ViewModels.UserEntity>
<h1>Admin Users</h1>
<ul>
@foreach (var user in Model)
{
<li>@user.Username</li>
}
</ul>
Upvotes: 1
Reputation: 506
Your view model contains an IEnumerable. The Model used in your view is an IEnumerable of view models. So essentially you have collections nested within a collection. I assume that you only want a single collection? In which case you either do not need the view model at all, or you should change the model used in your view to @model MyBlog.Areas.Admin.ViewModels.UserEntity
.
If the collections nested within a collection is on purpose, then I would suggest that you place everything inside the view model and still have @model MyBlog.Areas.Admin.ViewModels.UserEntity
in your view.
Upvotes: 0
Reputation: 37215
You declare a class UsersIndex
but you do not seem to use it. The controller needs to instantiate and pass a UsersIndex
value to the view, and the view's @model
needs to accept a UsersIndex
rather than an IEnumerable<UsersIndex>
Upvotes: 0
Reputation: 3009
<ul>
@foreach (var user in Model)
{
@foreach (var userVm in user.UsersVm)
{
<li>@userVm.Username</li>
}
}
</ul>
Upvotes: 2