2014-02-27 22 views
0

我在這個代碼中增加我,我無法解析。我在下面的代碼中出了什麼問題?asp.net mvc剃刀不能通過計數器增量

@{   
      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="[email protected]" 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; 
} 

回答

1

使用以下,來代替:

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

基本上,這會導致您item變量是由一個迭代(item.i)和實際項目(item.value)的一個對象。

0

首先,我會設置一個變量包含您QuotationDetailList

@{ var QuotationDetailList = Model.QuotationDetailList;} 

然後,在這裏使用一個for代替foreach

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

現在你可以使用引用項目您的變量和索引:

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