Search code examples
asp.net-mvcrazorrazor-2

asp.net mvc razor cannot pass counter increment


i am increment i in this code which i am not able to parse. what is wrong with i in the code below?

  @{        
            int i=0;
            }
@foreach (var item in Model.PortServiceTariffIncluded)
{


         <tr id="@("sp" + item.ServiceId)">
         <td>@item.ServiceName     <input type="hidden" name="QuotationDetailList[i].ServiceId" value="@item.ServiceId" /></td>
         <td>@item.ServiceCriteria</td>
         <td>@item.ItemBasis</td>
          <td>@Html.DropDownListFor(model => model.Currency, ViewBag.CurrencyDd as SelectList) <input type ="text" id="Amount@i" name="QuotationDetailList[i].Amount" /></td>
         <td><input type="hidden" value="@item.ServiceId" class="serviceslist" name="serviceslist" /><input type ="button" id="@item.ServiceId" name="btnremove" value="Remove" class="clsremove" /></td>
         </tr>
         i = i + 1;
} 

Solution

  • Use the following, instead:

    @foreach (var item in Model.PortServiceTariffIncluded.Select((value, i) => new { i, value })
    {
         <tr id="@("sp" + item.value.ServiceId)">
             <td>@item.ServiceName <input type="hidden" name="QuotationDetailList[item.i].ServiceId" value="@item.value.ServiceId" /></td>
             <td>@item.value.ServiceCriteria</td>
             <td>@item.value.ItemBasis</td>
             <td>@Html.DropDownListFor(model => model.Currency, ViewBag.CurrencyDd as SelectList) <input type ="text" id="[email protected]" name="QuotationDetailList[item.i].Amount" /></td>
             <td><input type="hidden" value="@item.value.ServiceId" class="serviceslist" name="serviceslist" /><input type ="button" id="@item.value.ServiceId" name="btnremove" value="Remove" class="clsremove" /></td>
         </tr>
    }
    

    Basically, this causes your item variable to be an object consisting of an iterator (item.i) and the actual item (item.value).