问题
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