此删除部分视图显示在 jquery 对话框中:
在调试模式下加载删除视图时,我看到模型的计数为 3,但是当我按下删除按钮时,我得到一个 NullReferenceException,该模型为 Null。
这个怎么可能?
@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>
}
控制器:
[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() });
}
更新:
该代码有效并且正在向控制器提供正确的 templateId:
<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>