ASP.NET MVC how to populate a collection to a 4 column table?

末鹿安然 提交于 2020-01-07 03:03:55

问题


I have a collection which I passed from my MVC controller to my view. In my view, I want to list the image and its description in a 4 column table. I did not use a grid.

So, If I get collection of 8, I will get a gallery list of 4 items in 2 rows of the table.

If I get 16, I will get 4 columns in 4 rows of the table.

In my code, I started off with add all the product items in one row. I need to add a new row after each set of 4 items.

How can I do that?

Is there a better control to use?

<table class="table-responsive">
            <tbody>
                <tr>
                    @foreach (var product in Model)
                    {

                        <td>

                            <img src=@product.Thumbnail style="width: 100px; height: 100px" />
                            <div class="col-md-6 col-xs-6 small">

                                @product.Title<br>
                                @product.Description<br>
                                @product.Audience<br>
                                @product.Company<br>
                                <label>Published : </label> @product.PubDate<br>
                                <label>Download : JPEG | PDF</label>
                            </div>
                        </td>
                    }
                </tr>
            </tbody>
        </table>

回答1:


I gess the most elegant way to do it is use linq to group all your products by 4 and then generate your table:

1 row for each group and 1 column for each product:

<table class="table-responsive">
    <tbody>
        @foreach (var productGroup in Model.Select((e, i) => new { Product = e, Grouping = (i / 4) }).GroupBy(e => e.Grouping))
        {
            <tr>
                @foreach (var product in productGroup.Select(x => x.Product))
                {
                    <td>
                        <img src=@product.Thumbnail style="width: 100px; height: 100px" />
                        <div class="col-md-6 col-xs-6 small">
                            @product.Title<br>
                            @product.Description<br>
                            @product.Audience<br>
                            @product.Company<br>
                            <label>Published : </label> @product.PubDate<br>
                            <label>Download : JPEG | PDF</label>
                        </div>
                    </td>
                }
            </tr>
        }
    </tbody>
</table>

Note Grouping = (i / 4) line. That's where you can change how many products you will have in a row.



来源:https://stackoverflow.com/questions/34454686/asp-net-mvc-how-to-populate-a-collection-to-a-4-column-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!