视图显示正确的值(OrderId = 3):
// GET:
public ActionResult ConfirmOrder()
{
//simplified code here
var model = new ConfirmOrderViewModel()
{
OrderId = 3,
};
return View(model);
}
查看效果很好(屏幕上显示的值)下面的Html部分:
@model Test.Models.Views.ConfirmOrderViewModel
@{
ViewBag.Title = "My title";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("ConfirmOrder", "Client", FormMethod.Post, new {
@class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<div class="row" style="padding:10px; margin:15px">
<div>
<div class="col-sm-3">
@Html.DisplayFor(m => m.OrderId)
</div>
</div>
</div>
}
ConfirmOrderViewModel类如下所示:
public class ConfirmOrderViewModel
{
public int OrderId { get; set; }
}
4。但是当它发布回来时,我只有空了
// POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ConfirmOrder(ConfirmOrderViewModel ViewModel)
{
//at this moment: ViewModel.OrderId = null
return RedirectToAction("Index");
}
控制器名称没问题,方法有效...没有错误。单击页面上的“确定”按钮后,单击“null”。什么会导致坏模型绑定?
答案 0 :(得分:2)
DisplayFor
辅助方法只会呈现OrderId
属性的值。顾名思义,它更适合向用户显示。如果您希望将OrderId
的值发布到http post action方法,则需要将其保留在表单内的表单字段中。
您可以保留form
@using (Html.BeginForm("ConfirmOrder", "Client"))
{
@Html.DisplayFor(m => m.OrderId)
@Html.HiddenFor(a=>a.OrderId)
<input type="submit" value="Confirm" />
}