As always, in every ASP.NET MVC application, I recommend using a presentation model that is adapted to the presentation requirements. So, in this view, you mentioned a table in which you want to group these users by 5 elements in a row:
public class MyViewModel { public int Key { get; set; } public IEnumerable<UsersClass> Users { get; set; } }
and then in the controller action:
public ActionResult Index() { // that your domain model => a list of UsersClass // could be coming from wherever you want var users = Enumerable.Range(1, 7).Select(x => new UsersClass { Id = x }); // Now let group those users into the view model: // We will have 5 elements per row var model = users .Select((u, index) => new { User = u, Index = index }) .GroupBy(x => x.Index / 5) .Select(x => new MyViewModel { Key = x.Key, Users = x.Select(y => y.User) }); return View(model); }
and finally, a strongly typed representation is pretty trivial:
@model IEnumerable<MyViewModel> <table> @foreach (var item in Model) { <tr> @foreach (var user in item.Users) { <td>@user.Id</td> } @for (int i = item.Users.Count(); i < 5; i++) { <td></td> } </tr> } </table>
Obviously, this representation could be further simplified using display templates:
@model IEnumerable<MyViewModel> <table> @Html.DisplayForModel() </table>
and in the corresponding display template:
@model MyViewModel <tr> @Html.DisplayFor(x => x.Users) @for (int i = item.Users.Count(); i < 5; i++) { <td></td> } </tr>
and UserClass display template:
@model UsersClass <td>@user.Id</td>
and the result:
source share