xDevil
xDevil

Reputation: 147

ASP.NET MVC 5 Deleting Row in database using AJAX

I am trying to delete rows in my table using Ajax so that the page does not refresh when I try to delete one row of the table. Here is the code I have, but at the moment pressing Delete does nothing:

Controller:

public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Main main = db.Mains.Find(id);
            if (main == null)
            {
                return HttpNotFound();
            }
            return View(main);
        }
[HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Main main = db.Mains.Find(id);
            db.Mains.Remove(main);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

The view:

<script>
$(document).ready(function () {
    $("#Delete").on("click", function () {
        var parent = $(this).parent().parent();
        $.ajax({
            type: "post",
            url: "@Url.Action("Delete","Main")",
            ajaxasync: true,
            success: function () {
                alert("success");
            },
            error: function (data) {
                alert(data.x);
            }
        });
    });
});
</script>

The actual link to delete from the table:

 <td>
      @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
      <a href="" id="Delete">Delete</a>
</td>

Please help me! Ty

Upvotes: 0

Views: 15503

Answers (3)

Luke
Luke

Reputation: 23680

You're not including the Id in the post in your AJAX method.

Without it, it won't be posting the Id to the DeleteConfirmed action method:

$(document).delegate('#Delete', 'click', function (e) {

    e.preventDefault();

    $.ajax({
            type: "post",
            url: "@Url.Action("Delete","Main")",
            ajaxasync: true,
            data: { id : $('input#idField').val() },
            success: function () {

                alert("success");

                // Perform redirect
                window.location.replace("@Url.Action('Index', 'Main')");
            },
            error: function (data) {
                alert(data.x);
            }
        });
});

As for it not redirecting after you post, that's because you're making your request using an AJAX request. If you return a redirect from your action method this won't be honoured by your page because it's a server side redirect.

You have to check for a success message and then redirect on success. I suggest the following:

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    Main main = db.Mains.Find(id);
    db.Mains.Remove(main);
    db.SaveChanges();
    return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
}

and to add this to your success (also shown above):

// Perform redirect
window.location.replace(@Url.Action('Index', 'Main'));

Your page is reloading the page because your link is instructing it to:

<a href="" id="Delete">Delete</a> // Navigate to current page

Add a tag hash in there, or add e.preventDefault() in your delegate function or both (also shown above):

<a href="#" id="Delete">Delete</a>

Upvotes: 5

anmarti
anmarti

Reputation: 5143

You have to pass your Id to the MVC Action. You are not actually passing it as parameter using the data option of the ajax jQuery method. Try debuggin you MVC Action and see what you are receiving in the Id parameter.

 <script>
$(document).ready(function () {
$("#Delete").on("click", function () {
    var parent = $(this).parent().parent();
    var myId = //Get here you id
    $.ajax({
        type: "post",
        url: "@Url.Action("Delete","Main")",
        data: {id:  myId },
        ajaxasync: true,
        success: function () {
            alert("success");
        },
        error: function (data) {
            alert(data.x);
        }
    });
});
});

You probably need to pass also the RequestVerificationToken

Upvotes: 0

XWiśniowiecki
XWiśniowiecki

Reputation: 1843

If you change:

return View(main);

to

return true;

will give you success on AJAX call.

Then dubug JS in browser to check if

alert("success");

in success is called

Upvotes: 0

Related Questions