Currently I have a ViewModel which is comprised of 2 lists of models. Displaying contents using the ViewModel is fine, however when I try to post I get a null reference exception.
public class DashboardViewModel
{
public IList<DashboardModel> dashboard { get; set; }
public IList<WidgetModel> widgets { get; set; }
}
Here is the form on the view
@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>
}
and here is my action
[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);
}
The null reference happens in the AddDashboard action I have set a breakpoint and realised that dashboardVM is null, the dashboard property is null