Logic inside table. for each loop for formatting
Is there a way I could limit the tds to 4 or any number in the following set up ..please see code below. Right now, its displaying all model items in one single row (as it should according to the code). If the items are a dozen, they are all displayed one single row.. I would like a way to display this four in each row instead of all in one row... (am I talking about table inside a table?) can this be done?
<table>
<tr>
@foreach (var item in Model)
{
<td>
@Html.DisplayFor(mod开发者_JS百科elItem => item.fld1)
@Html.DisplayFor(modelItem => item.fld2)
</td>
}
</tr>
</table>
You could group them:
@{
var chunkSize = 4;
var groupedResult =
from i in Model.Select((value, index) => new { Value = value, Index = index })
group i.Value by i.Index / chunkSize into g
select g;
}
<table>
@foreach (var result in groupedResult)
{
<tr>
@foreach (var item in result)
{
<td>
@Html.DisplayFor(modelItem => item.fld1)
@Html.DisplayFor(modelItem => item.fld2)
</td>
}
</tr>
}
</table>
Obviously the fact that you need to do this means that your view model is not adapted to this view. So adapt it and perform this grouping inside your controller action. Then your view will become simple and readable and not resemble some spaghetti code.
精彩评论