2009-10-04 83 views
0

考慮以下幾點:如何用一個鏈接刪除MVC中的多個項目?

管窺:

<%= Html.ListBox("BlackList", Model.Select(
        x => new SelectListItem 
          { 
            Text = x.Word, 
            Value = x.ID.ToString(), 
            Selected = Model.Any(y=> y.ID == x.ID) 
          }))%> 

主視圖:

<td><% Html.RenderPartial("GetBlackList", ViewData["BlackList"]); %></td> 

控制器:

 [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult DeleteWord(int[] wordIdsToDelete) 
    { 
     if (!ModelState.IsValid) 
      return View(); 
     try 
     { 
      _wordManager.DeleteWord(wordIdsToDelete); 
      return RedirectToAction("WordList"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

模型(WordManager)

public void DeleteWord(int[] idsToDelete) 
    { 
     var dataContext = GetLinqContext(); 
     var currentList = GetTabooWordList(); 

     foreach (var id in idsToDelete) 
     { 
      foreach (var item in currentList) 
      { 
       if (item.ID == id) 
       { 
         dataContext.BadWords.DeleteOnSubmit(item); 
       } 
      } 
     } 
     dataContext.SubmitChanges(); 
    } 

問題是如何正確傳遞參數 - idsForDel? I.E我必須將客戶端數據傳遞給服務器?

<%= Html.ActionLink("Delete Selected", "DeleteWord", "AdminWord", new { wordIds = idsForDel })%> 

我認爲這可以通過jQuery。有任何想法嗎?

回答

1

您可以綁定到使用模型綁定到一個列表 陣列(Haacked.com Model binding to a list,在這裏你可以看到如何綁定複雜類型以及)。

雖然我不是很滿意,我創建元素 這樣我就可以以它綁定到控制器的動作輸入參數序列化代碼,這個代碼的工作只是你想要什麼:

<script type="text/javascript"> 
function DeleteWords() { 
var el = $("<form></form>"); 
//for every selected item create new input element and insert it 
//inside of temporarty created form element 
var selItems = $('#BlackList option:selected').each(function(intIndex) { 

    //is important how you name input elements (as you can read in link I referenced) 
    el.append($('<input/>') 
    .attr({ type: "hidden", name: "wordIdsToDelete", value: $(this).val() }) 
    ); 
}); 

//make an ajax call with serialized temporary form 
$.ajax({ 
    type: "POST", 
    url: "/YourController/DeleteWord", 
    data: $(el).serialize(), 
    // error: HandleUnespectedError, 
    success: function(response) { 
     //handle response } 
});} 

希望這有助於...

1

這段代碼如何?

<%= Html.ActionLink("Delete Selected", "DeleteWord", 
         "AdminWord", new { id="send" })%> 
    <script type="text/javascript"> 
    $(function() { 
     $("#send").click(function() { 
     $.post(
      $("form:first").attr("action"), 
      $("#GetBlackList").serialize() 
     ); 
     }); 
    }); 
    </script> 

而且,如果兩個或多個記錄被刪除,則DeleteAllOnSubmit是好的。

dataContext.BadWords.DeleteAllOnSubmit(
    currentList.Where(item=>currentList.Containts(item.id)).ToList() 
); 
+0

我有你的主意,謝謝。但是如果我想傳遞一個數組呢? – Alexander 2009-10-05 05:47:36

+0

我錯了。 dataContext.BadWords.DeleteAllOnSubmit( currentList.Where(item => idsToDelete.Containts(item.id))。ToList() ); – takepara 2009-10-05 14:51:48