Paweł Duda
Paweł Duda

Reputation: 1783

ASP.NET MVC 4 - Ajax.ActionLink calls the method multiple times

This is the part of code in

<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" });

Upon clicking it is supposed to call the following action:

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

        return true;
    }

And it does - the note gets deleted. But the method is called 5 or 8 more times for some reason.

 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

What could be the cause of the extra calls?

Upvotes: 1

Views: 1836

Answers (2)

Paweł Duda
Paweł Duda

Reputation: 1783

This line was the cause:

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

I actually put it inside a "foreach" loop, causing it to be included multiple times. Once I moved it outside of that loop, the problem was fixed.

Note to self: you only include once.

Upvotes: 1

sridharnetha
sridharnetha

Reputation: 2248

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

change this to

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

Upvotes: 0

Related Questions