0

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

3
  • 2
    Delete does nothing is way too vague. What have you tried with debugging? How far have you gotten? Does your onclick get triggered, does it reach the mvc action, ... Please add at least the basic debugging info that you've tried. Commented Oct 9, 2015 at 9:07
  • Can you clarify if it is the delete that isn't working (in the database the row isn't deleted) or that it's just the page load that doesn't work... or both? Commented Oct 9, 2015 at 9:15
  • you want postback on DeleteConfirmed action after id is exist in your database? Commented Oct 9, 2015 at 9:19

3 Answers 3

5

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>
Sign up to request clarification or add additional context in comments.

5 Comments

it cannot find StatusCodeResult... should i just let VS generate it?
Is that because you've changed your return value from ActionResult to bool?
Ok, let me check it. I've just opened VS to have a look :P
Sorry, I misremembered it, it's HttpStatusCodeResult. Please see the update :)
0

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

1 Comment

I think you mean change return RedirectToAction("Index"); :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.