ASP.NET MVC Razor - если внутри для - PullRequest
1 голос
/ 18 октября 2011

Я пытаюсь вывести таблицу HTML, используя бритву. Сама таблица работает, но сейчас я пытаюсь добавить класс с именем "even" для каждой второй строки таблицы:

<table>
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < ViewBag.MyList.Count; i++)
        {
            var myObject = ViewBag.MyList[i];
            <tr @if (i % 2 == 0 ) { class="even" }>
                <td>myObject.Column1</td>
                <td>myObject.Column2</td>
                <td>myObject.Column3</td>
            </tr>
        }
    </tbody>
</table>

Очевидно, что-то не так с этим if-case внутри цикла, но как правильно написать это?

Ответы [ 2 ]

11 голосов
/ 18 октября 2011
<table>
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < ViewBag.MyList.Count; i++)
        {
            var myObject = ViewBag.MyList[i];
            <tr @{if (i % 2 == 0 ) { <text>class="even"</text> }}>
                <td>myObject.Column1</td>
                <td>myObject.Column2</td>
                <td>myObject.Column3</td>
            </tr>
        }
    </tbody>
</table>

Пожалуйста, взгляните на краткий справочник по синтаксису бритвы. Фил Хаак

http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

и сообщение Скотта Гатри о вашей проблеме

http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx

2 голосов
/ 11 октября 2013

Почему бы просто не использовать CSS3 для зебры?

tr:nth-child(2n+1) {
   background-color: #99ff99;
}
...