我正在尝试将POST请求的视图模型绑定到我的控制器操作中,并且看起来正在发送正确的参数,但我的viewmodels数据似乎是null
,尽管尝试了多项操作。我在视图中绑定了以下视图模型:
public class OrderDetailViewModel {
public List < OrderDetail > OrderDetails;
}
数据正确加载到我的视图中,这是主视图的样子:
<form class="form-horizontal" id="update-orderdetail" action="/orderdetail/update" method="post">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "alert alert-danger" })
<table class="table table-striped table-bordered table-hover results">
<thead>
... tr tags ...
</thead>
<tbody>
@Html.EditorFor(x => x.OrderDetails)
</tbody>
</table>
<div class="form-group">
<div class="pull-right">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
这是EditorTemplates/OrderDetail.cshtml
的样子:
@model CorinthVendorPortal.Models.OrderDetail
<tr>
<td>@Html.DisplayFor(x => x.PurchaseOrder)</td>
<td class="editable">
@Html.HiddenFor(x => x.ID)
@Html.HiddenFor(x => x.PurchaseOrder)
@Html.TextBoxFor(x => x.Price, new { @type = "number", @class = "form-control" })
</td>
<td>@Html.DisplayFor(x => x.StockCode)</td>
<td>@Html.DisplayFor(x => x.MStockDes)</td>
<td>@Html.DisplayFor(x => x.OrderQtyOrig)</td>
<td class="editable">
@Html.TextBoxFor(x => x.OrderQtyCur, new { @type = "number", @class = "form-control" })
</td>
<td>@Html.DisplayFor(x => x.DueDateOrig)</td>
<td class="editable">
@Html.TextBoxFor(x => x.DueDateCur, new { @type = "date", @class = "form-control" })
</td>
<td>@Html.DisplayFor(x => x.ShipDateOrig)</td>
<td class="editable">
@Html.TextBoxFor(x => x.ShipDateCur, new { @type = "date", @class = "form-control" })
</td>
</tr>
以下是OrderDetail
控制器的Update
方法的样子(我的模型的OrderDetails
属性为null
):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Update(OrderDetailViewModel model) {
var l = model; // model.OrderDetails is always null
....
return null;
}
以下是正在发布的参数:
OrderDetails[0].ID:1
OrderDetails[0].PurchaseOrder:0246298
OrderDetails[0].Price:8.85000
OrderDetails[0].OrderQtyCur:200.000000
OrderDetails[0].DueDateCur:
OrderDetails[0].ShipDateCur:
OrderDetails[1].ID:2
OrderDetails[1].PurchaseOrder:0246298
OrderDetails[1].Price:1.40000
OrderDetails[1].OrderQtyCur:750.000000
OrderDetails[1].DueDateCur:
OrderDetails[1].ShipDateCur:
任何帮助或建议都将不胜感激。
答案 0 :(得分:3)
您在视图模型中使用了字段,但MVC绑定仅适用于属性。
更改
public class OrderDetailViewModel {
public List<OrderDetail> OrderDetails;
}
到
public class OrderDetailViewModel {
public List <OrderDetail> OrderDetails { get; set; }
}
并且您的代码应该开始工作。