kathy
kathy

Reputation: 339

How to add a class to the first item in foreach in cshtml

 @foreach (var slider in Sliders)
 {
  <div class="item">
  ...
  </div>
 }

I am making a carousel with cshtml. How can I assign class "active" only to the first element in Sliders?

Thank you.

Upvotes: 0

Views: 3377

Answers (1)

Dai
Dai

Reputation: 155433

One way:

@{ Boolean first = true; }    
@foreach( var slider in Sliders ) {
    
    <div class="item @( first ? "active" : "" )">

    </div>

    first = false;
}

Another way:

@foreach( ( Slider s, Int32 idx ) in Sliders.Select( (s,idx) => (s,idx) ) ) {
    
    <div class="item @( index == 0 ? "active" : "" )">

    </div>
}

I wish C# would add "ambient variables" for foreach to expose the current item index without needing to use .Select( ( item, index ) => ... ).

Upvotes: 4

Related Questions