Search code examples
asp.net-mvcrazorasp.net-mvc-5

Foreach loop counter in MVC Razor


What I am attempting to accomplish is to set an alternating row on a table to a different CSS style.

My controller returns a simple list and passes that to the view by way of the ViewBag.

My View code is as follows:

@{
    int _recordCount = 1;
    foreach (var _oEstimateDetails in ViewBag.EstimateDetailData)
    {
        if (_recordCount == 1)
        {
            <tr class="EstimateDetailDataRow">
        }

        if (_recordCount == 1)
        {
            </tr><tr class="EstimateDetailDataAlternateRow">
            _recordCount = 0;
        }
        </tbody>
        <td class="EstimateDetailData">
            @_oEstimateDetails.EstimateLineDescription
        </td>
        <td class="EstimateQuantityData">
            @_oEstimateDetails.EstimateLineQuantity
        </td>
        <td class="EstimateRateData">
            @_oEstimateDetails.EstimateLineRate
        </td>
        <td class="EstimateLineTotalData">
            @(_oEstimateDetails.EstimateLineQuantity * _oEstimateDetails.EstimateLineRate)
        </td>
        </tr>
        _recordCount = _recordCount + 1;
    }
}

Since this is my 5th attempt to figure this out, I am about to pull my hair out. Any assistance would be most appreciative.


Solution

  • Assuming that <tbody> starts before programming code I think you are closing tbody to early here is snippet of code which imo should work:

    <tbody>
    @{    
        for(int i =0; i < ViewBag.EstimateDetailData.Count(); i++)
        {
            var _oEstimateDetails = ViewBag.EstimateDetailData.ElementAt(i);
    
            <tr class="@(i % 2 == 0 ? "EstimateDetailDataRow" : "EstimateDetailDataAlternateRow")">
            <td class="EstimateDetailData">
                @_oEstimateDetails.EstimateLineDescription
            </td>
            <td class="EstimateQuantityData">
                @_oEstimateDetails.EstimateLineQuantity
            </td>
            <td class="EstimateRateData">
                @_oEstimateDetails.EstimateLineRate
            </td>
            <td class="EstimateLineTotalData">
                @(_oEstimateDetails.EstimateLineQuantity * _oEstimateDetails.EstimateLineRate)
            </td>
            </tr>
        }
    }
    </tbody>