2012-05-05 53 views
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> 

回答

0

從如何您ActionLink的來看寫,else控制器的一部分將在您單擊刪除後執行(因爲內容將不在查詢字符串中)。該代碼返回沒有模型的View(),因此「模型爲空」異常。

編輯

有2個問題,我可以看到:

  1. 你的目標是需要POST的動作,所以你需要使用窗體回發,而不是ActionLink(使用GET)。
  2. 此操作需要templateId,所以路由屬性必須是。

所以我想這應該工作:

@{ using (Html.BeginForm()) { 
    <input type='hidden' name='templateId' value='@item.Id' /> 
    <input type='submit' value='Delete' /> 
}} 
+0

對不起,我忘了補充後刪除其從未執行的方法JsonDelete。當我點擊刪除鏈接時,我從來沒有涉及到你所說的其他部分,因爲這是HttpGet操作沒有發佈。 – Elisabeth

+0

@Elisa,謝謝,我覺得有些東西丟失了,但不太清楚是什麼。請看我更新的答案。 – McGarnagle