我有一个简单的购物车模型,其中包含一系列项目:
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);
}
}
不幸的是,当我点击Update Cart按钮时,它会调用我的Recalculate函数,但现在Items列表中的所有项都为null。如何保留项目并更新给定项目的数量?
在BeginForm函数中,我尝试传入当前模型,而不是传递模型......没有任何变化。有人能帮我解决这个问题吗?
答案 0 :(得分:5)
在适当的位置进行这些更改,事情就会开始起作用。请注意,虽然不会在模型中填充回发Price和TotalCost,因为相应的呈现项目是静态文本。这些可以在Controller中重新填充,或者在视图中添加隐藏字段,以便可以发布和重新填充这些字段。
<%using (Html.BeginForm("Recalculate", "ShoppingCart", FormMethod.Post))
<td><%: Html.TextBoxFor(m => m.Items[Model.Items.IndexOf(item)].Quantity)%></td>
//return RedirectToAction("Show", "ShoppingCart", model);
return View("Show", model);
答案 1 :(得分:1)
<%= Html.TextBox("Quantity", Model.Items[Model.Items.IndexOf(item)].Quantity ) %>
这是一篇不错的博文,值得一读:http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx