Question

I'm not quite sure what I am missing here, but I am having trouble adding a class='success' to a <tr> in a Partial View while iterating through a list in my Model.

My goal is to have the first row's tr to have the attribute class='success'

Here is the code I have:

@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>

When I step through the code, it goes into the special IsFirst section the first iteration and the else section on all other iterations.

But, when I use FireBug to view the source code, it is not writing the part: <tr class='success'> , just the <tr>.

Was it helpful?

Solution

I think the extra <tr> after your if statement might be causing the browser to ignore your html, as the html would actually be broken with two <tr> tags being rendered.

I would probably update the code to be more like;

@{ 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;

}

Since you are setting IsFalse to false after the first loop. Makes the code tidier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top