2013-03-22 24 views
0

我有一個WebGrid並用於行刪除這樣定義一個PartialView內的鏈接 - 作爲對電網項目被選中MVC,C#的WebGrid在PartialView,刪除行與阿賈克斯

@Html.ActionLink("Delete", "DeleteThis", "MyController", new { id = SelectedId }, null) 
<div id="MyGrid"> 
@{ 
    var grid = new WebGrid(Model.ListOfStuff, canSort: true, ajaxUpdateContainerId: "MyGrid"); 


    @grid.GetHtml() 
} 
</div> 

後,用戶可以單擊「刪除」鏈接從數據庫中刪除該行。

我的問題是,我想要調用的阿賈克斯呼叫更新刪除後的網格。我的類以Ajax方式工作,但我無法弄清楚如何讓「刪除」與Ajax協同工作。我的控制器代碼看起來像這樣 -

public ActionResult Index() 
    { 
     //CODE TO RETRIEVE THE MODEL 

     return PartialView("Index", model); 
    } 

    public ActionResult DeleteThis(string id) 
    { 
     ////CODE TO DELETE RECORD 

     return RedirectToAction("Index"); // I ALSO TRIED return PartialView("Index", model)   } 

任何洞察力將不勝感激。謝謝!

回答

0

監聽鏈接的點擊事件,並作出它執行刪除功能的操作方法Ajax調用。

確保您DeleteThis方法裝飾有HttpPost屬性。刪除應該總是HttpPost行動。不是GET操作。

[HttpPost] 
public ActionResult DeleteThis(string id) 
{ 
    try 
    { 
    // to do : delete 
    return Json(new { Status="Deleted"}); 
    } 
    catch(Exception ex) 
    { 
    //log the error 
    return Json(new { Status="Error"}); 
    } 
} 

從您的Action方法中,您返回的是JSON。在post方法的回調中,檢查Status屬性值以查看刪除操作是否成功。

$(function(){ 

    $("#SelectedId").click(function(e){ 
    e.preventDefault(); 

    var selectedItemId=34; // you need to get this from the grid; 

    $.post("@Url.Action("DeleteThis","Home")/"+selectedItemId,function(data){ 
     if(data.Status="Deleted") 
     { 
      //reload the page or just reload the partial view as needed 
      window.location.href=window.location.href; 
      // $("#GridContainer").load(@Url.Action("List","Users")"); 
     } 
    }); 

    }); 

}); 
+0

感謝Shyju!這似乎並不會刷新網格。那是對的嗎? – 2013-03-22 20:49:03

+0

@ABogus可以刷新或者整個頁面或簡單的重啓只使用另一個Ajax調用的網格(見註釋行是用'load'方法重新加載頁面的一部分) – Shyju 2013-03-22 22:24:56