如何使用单个链接删除MVC中的多个项目?

时间:2009-10-04 13:09:21

标签: c# jquery asp.net-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来实现。有什么想法吗?

2 个答案:

答案 0 :(得分: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()
  );

答案 1 :(得分:1)

您可以使用Model Binding to List绑定到数组 (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    }
});}

希望这会有所帮助......