This Delete partial view is shown in a jquery dialog:
When the delete view is loaded in debug mode I see that the Model has a count of 3
but when I press the Delete button I get a NullReferenceException, that Model is Null.
How can that be?
@using (@Html.BeginForm("Delete","Template",FormMethod.Post))
{
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Delete", "Delete", new { id = item.Id, returnUrl = Request.Url.PathAndQuery })
</td>
</tr>
}
</table>
}
Controller:
[HttpGet]
public ActionResult Delete()
{
string actionName = ControllerContext.RouteData.GetRequiredString("action");
if (Request.QueryString["content"] != null)
{
ViewBag.FormAction = "Json" + actionName;
var list = new List<Template> {
new Template{ Id = 1, Name = "WorkbookTest"},
new Template{ Id = 2, Name = "ClientNavigation"},
new Template{ Id = 3, Name = "Abc Rolap"},
};
return PartialView(list);
}
else
{
ViewBag.FormAction = actionName;
return View();
}
}
[HttpPost]
public JsonResult JsonDelete(int templateId, string returnUrl)
{
// do I get here no !
if (ModelState.IsValid)
{
return Json(new { success = true, redirect = returnUrl });
}
// If we got this far, something failed
return Json(new { errors = GetErrorsFromModelState() });
}
Update:
That code works and is supplying the correct templateId to the controller:
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@using (@Html.BeginForm((string)ViewBag.FormAction, "Template"))
{
@Html.Hidden("returnUrl", Request.Url.PathAndQuery);
@Html.Hidden("templateId", item.Id)
<input type='submit' value='Delete' />
}
</td>
</tr>
}
</table>
Judging from how your ActionLink is written, the else part of the controller is going to execute after you click delete (because content won’t be in the query string). That code returns View() with no model, hence the “model is null” exception.Edit
There are 2 problems I can see:
So I’m thinking this should work: