2012-07-25 116 views
0

我有一個網格,我希望能夠刪除行而不必從控制器操作返回新的結果集。Telerik MVC Grid Ajax刪除操作

這在我看來:

@(Html.Telerik().Grid<InterestTopicViewModel>() 
      .Name("Grid") 
      .DataKeys(keys => keys.Add(x => x.Id)) 
      .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.Image).ImageHtmlAttributes(new {style="margin-left:0"})) 
      .DataBinding(dataBinding => dataBinding.Ajax() 
             .Select("Select", "InterestTopic") 
             .Insert("Insert", "InterestTopic") 
             .Update("Update", "InterestTopic") 
             .Delete("Delete", "InterestTopic")) 
      .Columns(columns => 
         { 
         columns.Bound(x => x.Name); 
         columns.Command(commands => 
              { 
               commands.Edit().ButtonType(GridButtonType.Image); 
               commands.Delete().ButtonType(GridButtonType.Image); 
              }).Title("Actions"); 
         }) 
      .Editable(editing => editing.Mode(GridEditMode.InLine)) 
     ) 

這裏是在我的控制器:

[AcceptVerbs(HttpVerbs.Post)] 
    [GridAction] 
    public ActionResult Delete(int id) 
    { 
    InterestTopicViewModel interestTopicViewModel = this.InterestTopicPresenter.GetInterestTopic(id); 

    if (this.InterestTopicPresenter.DeleteInterestTopic(id)) 
     base.LogUserAction(UserActionLoggingType.DeleteInterest, interestTopicViewModel.Name); 

    return this.View(new GridModel(this.InterestTopicPresenter.GetList())); 
    } 

正如你所看到的,在我的控制,我必須返回結束函數的一個GridModel對象中的整個列表。如果我不這樣做,視圖將不會刷新。

是否有可能在控制器的幫助下刪除記錄,讓Telerik刪除javascript中相應行的div?

謝謝。

回答

3

如果你不害怕javascript和jQuery,它不是太困難。而不是使用網格命令欄和綁定,我通常只用一個模板連線它自己,像這樣的(用剃刀語法):

.Columns(columns => 
{ 
    columns.Bound(x => x.Name); 
    columns.Template 
    (
     @<text> 
      <a href="#" onclick="delete(this, @item.Id);">Delete</a> 
     </text> 
    ); 
}) 

產品的字段Telerik的在鍵入列模板綁定提供到你的模型。您的刪除功能不需要返回數據。您可以執行如下操作:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Delete(int id) 
{ 
    // call your code to delete the item here 
    return Json(new { resultCode = "success" }); 
} 

然後創建一個JavaScript函數以發佈到您的刪除函數。

function delete(sender, id) 
{ 
    $.ajax({ 
     type: "POST", // important, only perform deletes on a post 
     url: '/delete', 
     data: { id: id }, 
     success: function (result) 
     { 
      if (result.resultCode == "success") 
      { 
       var row = $(sender).closest("tr"); 
       row.remove(); 
      } 
     } 
    }); 
} 

就是這樣的。我不知道確切的語法,但希望這足以讓你開始。

+0

這是一個非常好的解決方案。只有一個問題;我的項目中有很多網格,如果我需要實現這樣的解決方案,我會爲此功能做很多代碼。在關鍵的地方,我肯定會這樣做,但對於其他人,我寧願有一個已經在Telerik框架中實現的解決方案。 – Samuel 2012-07-25 17:52:50