2016-09-24 1 views
0

私はカミソリビューで引用符を表示しようとしています。 ViewModelで引用符のリストをループすると、リスト内の他のすべての項目にblockquote-reverseのクラスを追加できる必要があります。カミソリビューでViewModelをループするときに、他のすべてのアイテムにCSSクラスを追加

下記を参照してください:あなたは%演算子を使用できるように

@model IEnumerable<CustomerViewModel> 

    @foreach (var customer in Model) 
    { 
     @* if index is odd *@ 
<blockquote> 
    <p>@customer.Name</p> 
    <footer>@customer.Quote</cite></footer> 
</blockquote> 

@* if index is even *@ 
<blockquote class="blockquote-reverse"> 
    <p>@customer.Name</p> 
    <footer>@customer.Quote</cite></footer> 
</blockquote> 
    } 

答えて

1

導入

@{int i = 0;} 
@foreach (var customer in Model) 
{ 
    var className = i % 2 == 0 ? "blockquote-reverse" : null; 
    i++; 
    <blockquote class="@className"> 
     <p>@customer.Name</p> 
     <footer><cite>@customer.Quote</cite></footer> 
    </blockquote> 
} 

:レコードのインデックスを追跡するための変数、およびMOD演算子(%)を使用し、正しいCSSクラスを選択するためにあなたがあなたのコード内で開始タグなしで終了タグ</cite>を持って、私が追加しました私の答えにタグを開きます。

+0

この回答をお寄せいただきありがとうございます。私はかなり私がC#で行うことができるかみそりで何かをすることができます忘れて... –

1

は、インデクサーのための変数を追加します

@{ var index = 0; } 
@foreach (var customer in Model) 
{ 
    if (index % 2 == 0) 
    { 
     .... // without class name 
    } 
    else 
    { 
     .... // with class name 
    } 
    index++; 
} 

サイドノート:あなたはまた、要素のスタイルをCSSの使用を検討することができます:nth-child(2n)セレクタを使用(例:this answerを参照)

関連する問題