maztt
maztt

Reputation: 12294

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;
} 

Upvotes: 0

Views: 1291

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239240

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).

Upvotes: 1

X3074861X
X3074861X

Reputation: 3819

First, I would set a variable to contain your QuotationDetailList :

@{ var QuotationDetailList = Model.QuotationDetailList;}

Then, use a for here instead of a foreach :

@for (var ListIndex = 0; ListIndex < Model.PortServiceTariffIncluded.Count(); ListIndex++)

Now you can reference items using your variable and the index :

<td>@QuotationDetailList[ListIndex].ServiceName     <input type="hidden" name="@QuotationDetailList[ListIndex].ServiceId" value="@QuotationDetailList[ListIndex].ServiceId" /></td>

Upvotes: 0

Related Questions