I have a generic list of objects that's passed to a view. Currently, each list item is displayed to the user row-by-row:
@foreach (var result in Model.SearchResults)
{
result.Address.TownCity
// ...
}
So each list item is displayed in its own row. Aesthetically this doesn't look the best, as there's quite a lot of white space left over.
What I want to do is something like this:
row 1 | list item 1 | list item 2
row 2 | list item 3 | list item 4
and so on.....
Is this something I have to do server-side i.e. put half of my list into another list and in the view have two foreach loops - each one filling a column, row-by-row? Or is there anyway this can be done in the view using razor?
You can do this to group each set of rows into 'batches' and then loop through each item in the batch.
@{
var batches = Model.SearchResult
.Select((x, i) => new { x, i })
.GroupBy(p => (p.i / 2), p => p.x);
}
@foreach(var row in batches)
{
<span>Row @row.Key</span>
@foreach(var item in row)
{
<span>| @item.Address.TownCity</span>
}
}
Alternatively you can use this; it's simpler, though a bit less elegant
@{
var resultArray = Model.SearchResult.ToArray(); // only necessary if SearchResult is not a list or array
}
@for(var i = 0; i < resultArray.Length; i++)
{
var item = resultArray[i];
if (i % 2 == 0)
{
<span>Row @(i / 2)</span>
}
<span>| @item.Address.TownCity</span>
}
This is very easy to do in CSS without adding additional load and complexity to your code
See this fiddle: http://jsfiddle.net/taBec/
@foreach (var result in Model.SearchResults)
{
<div class="box">@result.Address.TownCity</div>
}
Then in CSS:
.box { width: 150px; float: left; height:25px}
Your app runs faster and your design is responsive and fluid. I hope this helps.