2015-10-25 42 views
-1

我不确定是什么错,因为我对MVC非常陌生。这是一个购物车。客户可以查看购物车并编辑数量。已发布模型为空

在HttpPost ViewCart方法上,购物车始终为空,行数为零。

控制器:

public ActionResult ViewCart() { 
    var cart = (CartViewModel)Session["Cart"]; 
    return View(cart); 
} 

[HttpPost] 
public ActionResult ViewCart(CartViewModel cart) { 
    Session["Cart"] = cart; 
    return RedirectToAction("Order", "Checkout"); 
} 

查看:

@model CartViewModel 
using (Html.BeginForm()) { 
    <h2>Your cart</h2> 

    <table> 
     <thead> ... </thead> 
     <tbody> 
      @foreach (var item in Model.Lines) { 
       <tr> 
        <td>@Html.DisplayFor(modelItem => item.Article.Description)</td> 
        <td>@Html.EditorFor(modelItem => item.Quantity)</td> 
       </tr> 
      } 
     </tbody> 
    </table> 

    <input type="submit" value="Checkout"> 
} 

视图模型:

public class CartViewModel { 
    public List<Line> Lines { get; set; } 

    public CartViewModel() { 
     Lines = new List<Line>(); 
    } 
} 
+0

你不能使用'foreach'循环来生成表单控件 - 你需要使用'for'循环(检查html之前和之后了解差异) –

回答

0

尝试更改视图使用索引:

@model CartViewModel 
using (Html.BeginForm()) { 
    <h2>Your cart</h2> 

    <table> 
     <thead> ... </thead> 
     <tbody> 
      @for (int i = 0; i < Model.Lines.Count; i++) { 
       <tr> 
        <td>@Html.DisplayFor(m => Model.Lines[i].Article.Description) @Html.HiddenFor(m => Model.Lines[i].Article.Id)</td> 
        <td>@Html.EditorFor(m => Model.Lines[i].Quantity)</td> 
       </tr> 
      } 
     </tbody> 
    </table> 

    <input type="submit" value="Checkout"> 
} 
+0

谢谢你的工作。你甚至可以预见到我需要一个ID的隐藏字段。 – joakim0112