似乎不像@{index++;},我试过了@{int index++}, @(index++), @(int index++;)
此代码在使用MVC 2时不会抛出错误。这是它给我的关于索引的歧义警告。
@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>
试试:
@{int index = 0;}
@foreach (var line in Model.Lines)
{
<tr>
...
</tr>
index++;
}
这只是为了让Razor编译器高兴。这不是我推荐的解决方案。我建议您使用编辑器模板:
<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>
@Html.EditorFor(x => x.Lines)
</tbody>
<tfoot>
</tfoot>
</table>
,并在Line (~/Views/Shared/EditorTemplates/LineViewModel.cshtml
)的相应编辑器模板中,该模板将为Line集合的每个元素呈现:
@model LineViewModel
<td align="center">
@Html.TextBoxFor(x => x.Quantity)
</td>
<td align="left">
@Html.DisplayFor(x => x.Product.Name)
</td>
<td align="right">
@Html.DisplayFor(x => x.Product.Price)
</td>
<td align="right">
@Html.DisplayFor(x => x.CalculatedTotalPrice)
</td>
<td align="right">
@Html.ActionLink("Remove", "RemoveItem", new { productId = Model.Product.ProductID }, null)
</td>
看,没有丑陋的循环,弱类型的帮助,处理一些索引,等等…