0
此刪除局部視圖中示出了一個jquery對話框:模型是空的foreach在asp.net MVC的局部視圖
當刪除視圖在調試模式下加載我看到,該模型具有的計3 但當我按下刪除按鈕時,我得到一個NullReferenceException,該模型爲空。
這怎麼可能?
@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>
對不起,我忘了補充後刪除其從未執行的方法JsonDelete。當我點擊刪除鏈接時,我從來沒有涉及到你所說的其他部分,因爲這是HttpGet操作沒有發佈。 – Elisabeth
@Elisa,謝謝,我覺得有些東西丟失了,但不太清楚是什麼。請看我更新的答案。 – McGarnagle