Reputation: 1017
I am currently have a bunch of users sitting in a Membership Database and I want to be able to create a page in an MVC App that will be designed to pull back all the user information and display it on the page, I have created the solution below however I want be able to show the data in a Grid View instead of a list:
Controller:
public ActionResult Index()
{
var systemUsers = Membership.GetAllUsers();
return View(systemUsers);
}
View:
<ul>
<%foreach (MembershipUser user in Model){ %>
<li><%=user.UserName %></li>
<% }%>
</ul>
Can someone please tell me how I can get the users data and display it in a Grid View on the View? I was thinking that I could have a model that stores the data in which is then passed to the view and this model could be updated by the controller? But im unsure which datatype could be used to store the users data and then passed to the Grid View?
Thanks :-)
Upvotes: 2
Views: 1718
Reputation: 107267
Using MembershipUser
directly in your views isn't a very pure MVC approach, IMO.
IMO you could create a specific ViewModel containing just the fields you need to pass between the controller and the view, like so:
public class UserViewModel
{
public Guid UserId {get; set;}
public string UserName {get; set;}
// etc
}
After fetching all your users in your controller, you can then project the MembershipUsers across to your UserViewModel objects, e.g. using LINQ or AutoMapper, and then pass this enumeration into the View.
public ActionResult Index()
{
var systemUsers = Membership.GetAllUsers();
var vmUsers = new List<UserViewModel>();
foreach (MembershipUser u in Membership.GetAllUsers())
{
vmUsers.Add(new UserViewModel()
{
UserId = (Guid)u.ProviderUserKey,
UserName = u.UserName,
// etc
});
}
return View(vmUsers);
}
I'm not sure what you mean by 'GridView' (this is MVC, not WebForms), but the MVC WebGrid should do fine:
@model IEnumerable<MyNamespace.UserViewModel>
@{
var grid = new WebGrid(Model);
}
<div id="grid">
@grid.GetHtml()
</div>
Obviously you'll want to tweak the look and feel a bit.
Upvotes: 1