ASP.NET MVC 4 - Ajax.ActionLink多次调用该方法

时间:2013-11-06 18:51:40

标签: asp.net razor

这是

中代码的一部分
<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>
Ajax.ActionLink("Yes", "Delete", "Notes", new { id = item.NoteId }, new AjaxOptions { HttpMethod = "POST", OnComplete = "javascript:void(0);" }, new { id = item.NoteId, @class = "yes" });

点击后应该调用以下操作:

    [HttpPost]
    public bool Delete(int id)
    {
        Notes notes = db.Notes.Find(id);
        db.Notes.Remove(notes);
        db.SaveChanges();

        return true;
    }

它确实 - 笔记被删除了。但由于某种原因,该方法被称为5或8次。

 POST http://localhost:57904/Notes/Delete/41 500 (Internal Server Error) jquery-1.8.2.min.js:2
 POST http://localhost:57904/Notes/Delete/41 500 (Internal Server Error) jquery-1.8.2.js:8416
 POST http://localhost:57904/Notes/Delete/41 500 (Internal Server Error) jquery-1.8.2.min.js:2
 POST http://localhost:57904/Notes/Delete/41 500 (Internal Server Error) jquery-1.8.2.js:8416

额外通话的原因是什么?

2 个答案:

答案 0 :(得分:1)

这条线是原因:

<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>

我实际上把它放在一个“foreach”循环中,导致它被多次包含。一旦我将它移到该循环之外,问题就解决了。

自我注意:你只包括一次。

答案 1 :(得分:0)

Ajax.ActionLink("Yes", "Delete", "Notes", new { id = item.NoteId }, new AjaxOptions { HttpMethod = "POST", OnComplete = "javascript:void(0);" }, new { id = item.NoteId, @class = "yes" });

将此更改为

Ajax.ActionLink("Yes", "Delete", "Notes", new { id = item.NoteId }, new AjaxOptions { HttpMethod = "POST", OnComplete = "javascript:void(0);" }, new { @class = "yes" });