目前我有一个ViewModel,它由2个模型列表组成。使用ViewModel显示内容很好,但是当我尝试发布时,我得到一个空引用异常。
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为null,dashboard属性为null
答案 0 :(得分:2)
您的b.php
属性导致视图模型的// b.php
global $var;
echo $var;
(和[Bind]
)属性保持为null,因为dashboard
中未包含widgets
1}}列表。
尝试从您的操作参数中删除dashboard
并将其放在Include
本身上:
[Bind]
请参阅MSDN
答案 1 :(得分:0)
您的HttpPost
操作正在接收DashboardViewModel
,其中包含DashboardModel
的一系列内容,其中包含DashboardModel
。
但是,你并没有传递任何东西的集合,而是传递一个DashboardModel
。
更新您的操作以接受[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDashboard([Bind(Include = "DashID,DashName,CreatedBy,CreatedDate")] DashboardModel dashboardVM)
{
...
}
:
[Bind]
注意:DashboardModel
属性可能需要调整;您尚未提供 $http.get('/uploads?filename=' + imagename).success(function(response) {
$scope.img.push({imageph: response, image: item.image, url: item.url});
}).error(function (err) {
console.log('Error uploading file: ' + err);
});
类的定义。