目前,我有一个ViewModel,其中包含2个模型列表。使用ViewModel显示内容很好,但是当我尝试发布时,我得到一个null引用异常。
public class DashboardViewModel
{
public IList<DashboardModel> dashboard { get; set; }
public IList<WidgetModel> widgets { get; set; }
}
这是视图上的表格
@using (Html.BeginForm("AddDashboard", "Dashboard", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DashboardModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.dashboard.Last().DashName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.dashboard.Last().DashName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.dashboard.Last().DashName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="AddDashboard" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
}
这是我的行动
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDashboard([Bind(Include = "DashID,DashName,CreatedBy,CreatedDate")] DashboardViewModel dashboardVM)
{
if (ModelState.IsValid)
{
DashboardModel newDashboard = dashboardVM.dashboard.Last();
newDashboard.CreatedBy = User.Identity.GetUserId();
newDashboard.CreatedDate = DateTime.Now;
db.dashboards.Add(newDashboard);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(dashboardVM);
}
空引用发生在AddDashboard操作中,我设置了一个断点并意识到dashboardVM为空,dashboard属性为空
您的HttpPost
操作正在接收DashboardViewModel
,其中在内部包含的集合以及其他属性DashboardModel
。
但是,您没有传递任何东西的集合,而是传递了一个DashboardModel
。
更新您的操作以接受DashboardModel
替代:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDashboard([Bind(Include = "DashID,DashName,CreatedBy,CreatedDate")] DashboardModel dashboardVM)
{
...
}
注意:[Bind]
属性可能需要调整;您尚未提供DashboardModel
该类的定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句