Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc 3 razor & html table

I have UsersClass which will never have more then 10 items. How can I display user class with table in view something like this?

I want to show two rows with 10 cells

like image 468
Irakli Lekishvili Avatar asked Dec 12 '22 02:12

Irakli Lekishvili


1 Answers

As always and in every ASP.NET MVC application I recommend using a view model which is adapted to the requirements of the view. So in this view you mentioned a table in which you want to group those users by 5 elements per 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's 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's 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 the strongly typed view is pretty trivial:

@model IEnumerable<MyViewModel>
<table>
    @foreach (var item in Model)
    {
        <tr>
            @foreach (var user in item.Users)
            {
                <td>@user.Id</td>
            }

            <!-- That's 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 view could be simplified even further 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 the UsersClass display template:

@model UsersClass
<td>@user.Id</td>

and the result:

enter image description here

like image 124
Darin Dimitrov Avatar answered Dec 14 '22 14:12

Darin Dimitrov