How properly generate bootstrap grid via loop using Razor?

后端 未结 2 491
甜味超标
甜味超标 2020-12-02 01:56

I use ASP.NET MVC and bootstrap. I have many objects (>2) in collection and for each need a

but with only 2 cols in a row. How to
相关标签:
2条回答
  • 2020-12-02 02:18

    Using a combination of the split method found here (which I turned into a helper method)

    https://www.jerriepelser.com/blog/approaches-when-rendering-list-using-bootstrap-grid-system/

    and a for loop I managed to achieve the grid with indexed items

    public static class SplitListHelper
    {        
        public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
        {
            for (var i = 0; i < (float)array.Length / size; i++)
            {
                yield return array.Skip(i * size).Take(size);
            }
        }
    }
    


    @if (Model != null)
    {
        int rowCount = 0;
        foreach (var row in Model.ToArray().Split(4))
        {
            <div class="row">
                @for (int i = 0; i < row.Count(); i++)
                {
                    <div class="col-xs-3">
                        @Html.DisplayFor(m => Model[rowCount + i].Name)
                        @Html.CheckBoxFor(m => Model[rowCount + i].Selected)                    
                    </div>
                }
            </div>
            rowCount += 4;
        }                       
    }
    
    0 讨论(0)
  • 2020-12-02 02:35

    Close the row div and start a new one inside the loop on every 2nd iteration

    <div class="row">
        @for (int i = 0; i < Model.Count; i++)
        {
            if (i > 0 && i % 2 == 0)
            {
                @:</div><div class="row"> // close and start new row
            }
            <div class="col-xs-6">
                @Html.TextBoxFor(o => o[i].Value)
            </div>
        }
    </div>
    
    0 讨论(0)
提交回复
热议问题