ASP.NET MVC Razor - 如果内在的话

haa*_*gel 1 asp.net-mvc razor

我正在尝试使用razor输出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>
Run Code Online (Sandbox Code Playgroud)

这个if-case在循环中显然有问题,但是写这个的正确方法是什么?

dkn*_*ack 11

<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>
Run Code Online (Sandbox Code Playgroud)

请查看phil haack的razor语法快速参考

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

和scott guthries发布关于你的问题

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