Apply different DIV based on record id in For each loop

HDeveloper2021 1 Reputation point
2021-07-17T16:16:32.093+00:00

I am working on MVC 5. Using WEB API, fetch the data now it is time to apply the HTML PAGE design and CSS.
@foreach (var item in Model)
{
if (Model.First() == item)
{
///APPLY FIRST RECORD CSS:- Works FINE
}
else {
<div class="row">
<div class="col-sm-4">
</div>
</div>
}
}

In the else portion, every time it generates the new ROW for a SINGLE record. But I am interested to display record 2 3 4 in SECOND ROW. 5 6 7 Record in the THIRD ROW and so on.

ASP.NET MVC
ASP.NET MVC
A Microsoft web application framework that implements the model-view-controller (MVC) design pattern.
981 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 43,906 Reputation points
    2021-07-17T17:28:51.137+00:00

    Just use mod operator.

    @{
       var row = 0;
       foreach (var item in Model)
       {
           ++row;
           if (row == 1)
           {
               ///APPLY FIRST RECORD CSS:- Works FINE
            }
            else if ((row + 1) % 3 == 0){
                 // 2,5,8…
                 <div class="row">
                 <div class="col-sm-4">
                  </div>
                  </div> 
           } else {
                // other
           }
    }
    
    0 comments No comments

  2. Yijing Sun-MSFT 7,041 Reputation points
    2021-07-19T03:05:36.567+00:00

    Hi @HDeveloper2021 ,
    I suggest you could do like this:

     @model IList<WebMvc.Models.tblTest>  
        @{  
            ViewBag.Title = "Index";  
            Layout = "~/Views/Shared/_Layout.cshtml";  
        }  
          
    <h2>Index</h2>  
    @for (var i = 0; i < Model.Count(); i += 3)  
        {  
            <div class="row">  
                @{  
                    int j = 0;  
                    for (; j <= 2 && i + j < Model.Count(); j++)  
                    {  
                        <div class="col-sm-4">  
                            @Model[i + j].testId  
                        </div>  
                    }  
                }  
            </div>  
        }  
          
    

    Result:
    TQBiH.png

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments