Asp.net mvc 发布的模型为空
我不确定出了什么问题,因为我是MVC的新手。这是一辆购物车。客户可以查看他们的购物车并编辑数量 在HttpPost ViewCart方法中,cart始终为空,行数为零 控制器:Asp.net mvc 发布的模型为空,asp.net-mvc,Asp.net Mvc,我不确定出了什么问题,因为我是MVC的新手。这是一辆购物车。客户可以查看他们的购物车并编辑数量 在HttpPost ViewCart方法中,cart始终为空,行数为零 控制器: public ActionResult ViewCart() { var cart = (CartViewModel)Session["Cart"]; return View(cart); } [HttpPost] public ActionResult ViewCart(CartViewModel c
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
使用(Html.BeginForm()){
你的车
...
@foreach(模型行中的var项){
@DisplayFor(modeleItem=>item.Article.Description)
@EditorFor(modelItem=>item.Quantity)
}
}
视图模型:
public class CartViewModel {
public List<Line> Lines { get; set; }
public CartViewModel() {
Lines = new List<Line>();
}
}
公共类CartViewModel{
公共列表行{get;set;}
公共CartViewModel(){
行=新列表();
}
}
尝试将视图更改为使用索引:
@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">
}
@model CartViewModel
使用(Html.BeginForm()){
你的车
...
@对于(int i=0;iModel.Lines[i].Article.Description)@Html.HiddenFor(m=>Model.Lines[i].Article.Id)
@Html.EditorFor(m=>Model.Lines[i].Quantity)
}
}
您不能使用foreach
循环来生成表单控件-您需要使用for
循环(在前后检查html以了解差异),这非常有效。你甚至预见到我需要一个隐藏的身份证。
@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">
}