Search code examples
c#asp.net-mvcrazorlayoutrepeater

code based repeater in Razor c#


I have the following Razor code:

@foreach (var row in Model)
        {
           <div><img src="~/Content/images/flickabase/@row.FlickaMasterImage" alt="@row.FlickaMasterImageCaption" class="img-thumbnail" width="100" heigh="100"/>
            <a href="/flickas/flickaid/@row.Id/flickaname/@row.FlickaName.Trim()">@row.FlickaName</a> </div> 
        }

This prints out a series of thumbnails and boat name. Like this.

single column display

The problem is that I want to write out four columns with the data running top to bottom, left to right. This used to be easy with .net repeater control but I can't see how I can easily do this with Razor. Is there an easy way to do this? The best idea I have come up with is to count the rows. Divide by four and then (since I am using Bootstrap) create a grid column for each batch.

Norb.


Solution

  • thanks for all your comments.

    This is how I solved it in the end. I used Skip and Take on the model to get batches of the data. There is never going to be masses of data and when it grows I'll revisit in the future. I ditched the images in the end. The four batches are written out one by one inside a Bootstrap col which does the layout.

    I am sure there is a more elegant way but this will do for now.

    @{
        Layout = "Shared/_Layout.cshtml";
        ViewBag.Title = "Flicka Names";
        var i = Model.Count(); // count rows
        var size = i/4; // get the batch size
    
        var first = Model.Take(size);
        var second = Model.Skip(size).Take(size); 
        var third = Model.Skip(size * 2).Take(size);
        var fourth = Model.Skip(size * 3).Take(size);
    }
    
    <h1>Flicka Names</h1>
    <p>There are @i Flickas in our system.</p>
    
    <div class="col-sm-3">
    
        @foreach (var row in first)
            {
               <div>
                <a href="/flickas/flickaid/@row.Id/flickaname/@row.FlickaName.Trim()">@row.FlickaName</a> </div>
    
            }
        </div>
    
    <div class="col-sm-3">
        @foreach (var row in second)
            {
            <div>
                <a href="/flickas/flickaid/@row.Id/flickaname/@row.FlickaName.Trim()">@row.FlickaName</a></div>
    
            }
    </div>
    
    
    <div class="col-sm-3">
        @foreach (var row in third)
            {
            <div>
                <a href="/flickas/flickaid/@row.Id/flickaname/@row.FlickaName.Trim()">@row.FlickaName</a>
            </div>
    
        }
    
    </div>
    
    <div class="col-sm-3">
        @foreach (var row in fourth)
                {
            <div>
                <a href="/flickas/flickaid/@row.Id/flickaname/@row.FlickaName.Trim()">@row.FlickaName</a>
            </div>
    
        }