Unable to list Users in a view using MVC3
I am trying to list all users in a view but 开发者_如何学Cwith no success. There are loads of questions here referring to the same problem and I have tried most of the replies, but for some reason I cannot get it to work. The following is the simplest implementation I could come up with but the error message is the same whatever method I use.
Compiler Error Message: CS1061: 'object' does not contain a definition for 'UserName' and no extension method 'UserName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
@{
ViewBag.Title = "Admin";
}
<ul>
@foreach (var user in Membership.GetAllUsers())
{
<li>Name: @user.UserName </li>
}
</ul>
Any suggestions or advice would be greatly appreciated. Many Thanks
Use MembershipUser
instead of var
.
@foreach (MembershipUser user in Membership.GetAllUsers())
{
<li>Name: @user.UserName</li>
}
This being said I hope you realize that this is a total anti-MVC pattern. It's not the views responsibility to pull/fetch data from some stores. They should only use data that it is being passed to them from a controller action under the form of a strongly typed view model.
So here's the correct way to do this.
As always you start by defining a view model which will contain the data that you need to show in your view (in this case a list of usernames):
public class UserViewModel
{
public string Name { get; set; }
}
then a controller action:
public ActionResult Index()
{
var model = Membership
.GetAllUsers()
.Cast<MembershipUser>()
.Select(x => new UserViewModel
{
Name = x.UserName
});
return View(model);
}
then a corresponding strongly typed view:
@model IEnumerable<UserViewModel>
<ul>
@Html.DisplayForModel()
</ul>
and a display template for a given user which will be rendered for each item of the model collection (~/Views/Shared/DisplayTemplates/UserViewModel.cshtml
):
@model UserViewModel
<li>Name: @Model.Name</li>
精彩评论