I am trying to pull all the USERS created in the database(AspNetUsers) using Register form. I have read several similar issues but can't fix this issue.Usually the reason for this error is when we try to pull a list from the controller but in view we do not specify IEnumerable at top.However I have added that as well, please see the code below. Million thanks for any help in advance.
@model IEnumerable<TimeSheet.ViewModel.UserViewModel>
@using TimeSheet.Models
@{
ViewBag.Title = "Index";
}
<h2>Manage User</h2>
<br/>
<table class="table table-condensed table-hover">
<tr class="table-header">
<th>
@Html.DisplayNameFor(m => m.Email)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(m => item.Email)
</td>
<td>
@Html.Partial("_TableButtonPartial", new IndividualButtonPartial { UserId = item.Id })
</td>
</tr>
}
</table>
UserController
public class UserController : Controller
{
TimeSheetEntities db = new TimeSheetEntities();
/* private ApplicationDbContext db;
public UserController()
{
db = ApplicationDbContext.Create();
}*/
// GET: User
public ActionResult Index()
{
return View(db.AspNetUsers.ToList());
//return View();
}
}
UserViewModel
namespace TimeSheet.ViewModel
{
public class UserViewModel
{
[Required]
public string Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string FullName { get { return this.FirstName + " " + this.LastName; } }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
public string UserRole { get; set; }
public string Manager { get; set; }
}
}
Since your are using mostly email,the easiest way to fix would be to change a model class
@model List<AspNetUser>
or if you want to save some.network traffic, you can go a long way
create this viewmodel
public class UserGridViewModel
{
public string Id { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
fix the action
public ActionResult Index()
{
var model= db.AspNetUsers.Select(i=> new UserGridViewModel {
Id=i.Id,
Email=i.Email
}).ToList();
return View(model);
}
and view
@model List<TimeSheet.ViewModel.UserGridViewModel>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.