如果/ else条件,则无法在Razor视图中编写HTML

时间:2014-05-09 15:15:24

标签: asp.net-mvc razor asp.net-mvc-5

我不太确定我在这里缺少什么,但是我在部分视图中向class='success'添加<tr>时遇到问题,而我在模型中迭代了一个列表。

我的目标是让第一行的tr具有属性class='success'

这是我的代码:

@model List<DxRow>

<div class="row">
    <table class="table" id="diagnosis">
        <tr id="header-row">
            <th>Dx Code</th>
            <th>Dx Description</th>
            <th>Dx Date</th>
            <th>OnSet Or Ex</th>
            <th>Dx Order (Top is Primary)</th>
        </tr>

    @{ bool IsFirst = true; }
    @foreach (DxRow r in Model)
    {
           if (IsFirst)
           { 
               Html.Raw("<tr class='success'>");
               IsFirst = false;
           }
           else
           {
               Html.Raw("<tr>");
           }
       <tr>

        <td>@r.dxCode</td>
        <td>@r.dxDescription</td>
        <td>@r.dxDate</td>
        <td>@r.dxType</td>
        <td>
            <span class='up'><i class='icon-arrow-up bigger-160' style='color:green'></i></span>&nbsp;&nbsp;
            <span class='down'><i class='icon-arrow-down bigger-160' style='color:red'></i></span>&nbsp;&nbsp;
            <span class='top'><i class='icon-star bigger-160' style='color:goldenrod'></i></span>&nbsp;&nbsp;
            <span class='delete'><i class='icon-trash bigger-160' style='color:red'></i></span>
        </td>
    </tr>
    }
</table>

当我单步执行代码时,它会进入第一次迭代的特殊IsFirst部分和所有其他迭代的else部分。

但是,当我使用FireBug查看源代码时,它不会编写部分:<tr class='success'>,而只是<tr>

1 个答案:

答案 0 :(得分:2)

我认为<tr>语句之后的额外if可能会导致浏览器忽略您的html,因为html实际上会被渲染两个<tr>标记。

我可能会更新代码更像;

@{ bool IsFirst = true; }
@foreach (DxRow r in Model)
{

   <tr class="@( IsFirst ? "success" : "")">

       <td>@r.dxCode</td>
       <td>@r.dxDescription</td>
       <td>@r.dxDate</td>
       <td>@r.dxType</td>
       <td>
           <span class='up'><i class='icon-arrow-up bigger-160' style='color:green'></i></span>&nbsp;&nbsp;
            <span class='down'><i class='icon-arrow-down bigger-160' style='color:red'></i></span>&nbsp;&nbsp;
            <span class='top'><i class='icon-star bigger-160' style='color:goldenrod'></i></span>&nbsp;&nbsp;
            <span class='delete'><i class='icon-trash bigger-160' style='color:red'></i></span>
        </td>
    </tr>

    IsFirst = false;

}

由于您在第一个循环后将IsFalse设置为false。使代码更整洁。