我有一个简单的购物车模式,其中载有下列物品清单:
public class ShoppingCart
{
public List<Item> Items { get; set; }
public double Tax { get; set; }
// ... some other properties
}
public class Item
{
public string Name { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
public double TotalCost { get { return Quantity * Price; } }
}
我想修改某一项目的数量,我提出以下看法:
<%using (Html.BeginForm("Recalculate", "ShoppingCart", Model))
{ %>
<table id="cartTable" border ="5px" cellpadding="5px" cellspacing="5px" width="640">
<tr>
<td><b>Item Name</b></td>
<td><b>Item Qty</b></td>
<td><b>Item Price</b></td>
<td><b>Subtotal</b></td>
</tr>
<%
if (Model != null && Model.Items != null)
{
foreach (ShoppingCart.Models.Item item in Model.Items)
{
%>
<tr>
<td><%: item.Name%></td>
<td><%: Html.TextBoxFor(m => m.Items[Model.Items.IndexOf(item)], new { @Value = item.Quantity })%></td>
<td><%: String.Format("{0:C}", item.Price)%></td>
<td><%: String.Format("{0:C}", item.TotalCost)%></td>
</tr>
<%
}
}
%>
<!-- some other rows/columns go here -->
</table>
<input type="submit" value="Update Cart" />
<%} %>
我的控制者:
public class ShoppingCartController : Controller
{
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Show(ShoppingCart model)
{
if (model!= null && model.Items == null)
{
List<Item> items = new List<Item>();
items.Add(new Item { Name = "Hat", Price = 20.0, Quantity = 1 });
items.Add(new Item { Name = "Snowboard", Price = 430.0, Quantity = 1 });
items.Add(new Item { Name = "Goggles", Price = 24.0, Quantity = 3 });
model.Items = items;
model.Tax = 6.5;
}
return View(model);
}
[HttpPost]
public ActionResult Recalculate(ShoppingCart model)
{
if (model != null && model.Items!=null)
{
foreach (Item item in model.Items)
{
if (item.Quantity == 0)
{
model.Items.Remove(item);
}
else if (item.Quantity < 0)
{
ModelState.AddModelError("error", "The quantity for " + item.Name + " must not be smaller than 0.");
}
}
}
return RedirectToAction("Show", "ShoppingCart", model);
}
}
不幸的是,当我点击《最新消息》Cartutton时,它叫我重新计算功能,但现在项目清单上的所有项目都是无效的。 我怎么能够保留这些项目并更新某个项目的数量?
在BeginForm职能中,我尝试采用目前的模式,而不是通过模式......没有任何变化。 谁能帮助我看上去?