The issue is a type mismatch between what your controller action is passing to the view and what the view is expecting.
var result = await db.Users.ToListAsync();
return View(result );
result
is of type List<IdentityUser>
because that is what ToListAsync
will return. However in your view you are using this
@model List<ContactManager.Models.UserModel>
That means the view is expecting UserModel
. Since you are passing a different type to the view it is raising the exception. To work around this the correct solution is to convert the IdentityUser
instances to UserModel
before passing that to the view. Unfortunately your existing model is not going to work. You are deriving from IdentityUser
but you won't be able to create instances of that type nor can you magically associate them with a new UserModel
instance. Instead you should accept (generally in the constructor or by using object initializer syntax) the IdentityUser
you want to have the model represent. Convert each of the users before passing that on to the view.
public class UserModel
{
//In general you should have a default constructor for models otherwise you run into binding issues
public UserModel() { }
//Converts a user to a model
public UserModel ( IdentityUser user ) {
//Set whatever properties you need
UserName= user.UserName;
Email = user.Email;
}
//Expose whatever properties your view will need, just making some up here
public string UserName { get; set; }
public string Email { get; set; }
}
//Do the conversion from user to model
var result = await db.Users.ToListAsync();
var models = result.Select(x => new UserModel(x));
return View(models);