shaadi
shaadi

Reputation: 171

How to add div tag after fixed number of iteration in mvc

I am using Umbraco (mvc) with bootstrap.My template use partial view to load name and job title of staff in template. How I can add div (new row) after 4 iteration.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage

@{
    var selection = Model.Content.Site().FirstChild("aboutUs").Children("staff")
                        .Where(x => x.IsVisible());
}
    @foreach(var item in selection){
          <div class="row team">
                <div class="col-sm-3">
                    <div class="thumbnail-style">
                        <h3><a>@item.GetPropertyValue("fullName")</a> <small>@item.GetPropertyValue("jobTitle")</small></h3>
                    </div>
                </div>
          </div>
          }

Difficulty:

I want to add

 <div class="row team">
 </div>

after every 4th

<div class="col-sm-3">
</div>

Upvotes: 1

Views: 325

Answers (3)

Mivaweb
Mivaweb

Reputation: 5732

A more easier solution would be the use of the Umbraco helper method InGroupsOf(columns).

@foreach(var group in selection.InGroupsOf(4))
{
   <div class="row team">
      @foreach(var item in group)
      {
         <div class="col-sm-3">
             <div class="thumbnail-style">
                 <h3><a>@item.GetPropertyValue("fullName")</a> <small>@item.GetPropertyValue("jobTitle")</small></h3>
             </div>
         </div>
      }
   </div>
}

Upvotes: 2

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

Try:

 @foreach(var obj in selection.Select((item, index) => new {item, index}))
 {
          if(obj.index==0||obj.index%4==0){
              @Html.Raw("<div class='row team'>")
          }
                <div class="col-sm-3">
                    <div class="thumbnail-style">
                        <h3><a>@obj.item.GetPropertyValue("fullName")</a> <small>
                            @obj.item.GetPropertyValue("jobTitle")</small></h3>
                    </div>
                </div>
           @if((obj.index+1)%4==0||obj.index+1==selection.Count()){
           @Html.Raw("</div>")
          }
}

Upvotes: 1

akshay tilekar
akshay tilekar

Reputation: 15

 -  It will works, Use for loop instead of foreach loop and then just add logic

        @for (int i = 1; i < selection.Count; i++)
        {
        var item = selection[i];
        <div class="row team">
            <div class="col-sm-3">
               <div class="thumbnail-style">
                @if (i % 5 == 0)
                {
                    <div class="col-sm-3">
                        <h4 >D @item</h4> <!--your actual html code-->
                    </div>
                }
                else
                {
                    <h4 style="color:red">D @item</h4> <!--your actual html code-->
                }
            </div>
        </div>
    </div>
           }

Upvotes: 0

Related Questions