Asp.net mvc 3 razor & html table

I have a UserClass that will never have more than 10 items. How can I display a user class with a table in the form of something like this?

I want to show two rows with 10 cells

+4
source share
2 answers

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> } <!-- That just to fill the row with the remaining td if we have less than 5 users. Obviously depending on your requirements you could use a single td with a calculated colspan or something else --> @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:

enter image description here

+10
source

Not sure if this is exactly what you are looking for, but if it is not, you can easily change it:

 @* Check to make sure your user class is not null *@ @if (Model.UserClass != null) { <table> for (int i = 1; i <= 2; i++) { <tr> for (int j = 1; j <= 5; j++) { <td>if (Model.UserClass[(j*i)-1] != null) { Model.UserClass[(j*i)-1] }</td> } </tr> } </table> } 

I wrote this pretty quickly, but it should be close to what you need.

+3
source

Source: https://habr.com/ru/post/1411304/


All Articles