It does not seem to like @{index++;} , I have tried
@{int index++}, @(index++), @(int index++;)
This code didn’t throw errors when used with MVC 2.
Here’s it’s giving me
ambiguity warnings about index.
@model CartTest.Models.Cart
@{
ViewBag.Title = "Index";
}
<h2>Cart Index</h2>
<table width="80%" align="center">
<thead><tr>
<th align="center">Quantity</th>
<th align="left">Item</th>
<th align="right">Price</th>
<th align="right">Subtotal</th>
</tr></thead>
<tbody>
@{int index = 0;}
@foreach (var line in Model.Lines)
{
<tr>
@Html.Hidden("Lines.Index", index);
<td align="center">@Html.TextBox("Lines[" + index + "].Quantity",line.Quantity)</td>
<td align="left">@line.Product.Name</td>
<td align="right">@line.Product.Price</td>
<td align="right">@(line.Quantity * line.Product.Price)</td>
<td align="right">@Html.ActionLink("Remove", "RemoveItem", new { productId = line.Product.ProductID }, null)</td>
</tr>
@{index++;}
}
</tbody>
<tfoot>
</tfoot>
</table>
Try like this:
Now that’s just to make the Razor compiler happy. It’s not a solution I recommend. The real solution I would recommend you is to use editor templates:
and inside the corresponding editor template of a Line (
~/Views/Shared/EditorTemplates/LineViewModel.cshtml) which will be rendered for each element of the Line collection:See, no more ugly loops, weakly typed helpers, dealing with some indexes, etc… Everything works by conventions.