它似乎不喜欢@ {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>
答案 0 :(得分:0)
试试这样:
@{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>
看,没有更丑陋的循环,弱类型的帮助器,处理一些索引等等...一切都按惯例工作。