Membership and Looping through the Site Users in MVC with Razor
There are so few examples of this out there - it took me forever to find it but it was such a simple, elegant solution that I thought I would share.
So in your Action you don't want to use the MembershipCollection directly as it will return a string that will not be IENumerable - instead you will want to use your UsersContext
This will go in your Controller
[Authorize(Roles = "Admin")]
public ActionResult MembersIndex()
{
using (var ctx = new UsersContext())
{
return View(ctx.UserProfiles.OrderBy(x => x.UserId).ToList());
}
}
Then in your Razor MVC Page you will do something like this:
@foreach ( var user in Model){
@user.UserName - @user.UserEmail
}
You don't need to declare a model in the top of your page.
So in your Action you don't want to use the MembershipCollection directly as it will return a string that will not be IENumerable - instead you will want to use your UsersContext
This will go in your Controller
[Authorize(Roles = "Admin")]
public ActionResult MembersIndex()
{
using (var ctx = new UsersContext())
{
return View(ctx.UserProfiles.OrderBy(x => x.UserId).ToList());
}
}
Then in your Razor MVC Page you will do something like this:
@foreach ( var user in Model){
}
You don't need to declare a model in the top of your page.
Comments