此删除部分视图显示在jquery对话框中:
在调试模式下加载删除视图时,我看到模型的计数为3 但是当我按下Delete按钮时,我得到一个NullReferenceException,那个Model是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>
答案 0 :(得分:0)
根据您的 ActionLink 的编写方式判断,点击删除后,控制器的 else 部分将会执行(因为内容不会出现在查询字符串中)。该代码返回没有模型的View(),因此“model is null”异常。
修改强>
我可以看到两个问题:
所以我认为这应该有效:
@{ using (Html.BeginForm()) {
<input type='hidden' name='templateId' value='@item.Id' />
<input type='submit' value='Delete' />
}}