leora
leora

Reputation: 196429

calling controller action from javascript

i have a link that calls into a javascript to give a confirmation:

$("a.delete").click(function() {
    var name = $(this).parent().prev('td').prev('td').text();
    jConfirm('Are you sure you want to delete the following member:' + name, 'Member Delete', function(r) {
    });
});

i want, if the user clicks yes to call a controller action similar to what this code does:

 <%= Html.ActionLink("Delete", "Delete", new { id = item.Mail_ID })%>

how can i get the functionality of the jquery confirmation popup but still get the same results after that i would with the actionlink.

Upvotes: 0

Views: 2601

Answers (1)

Alconja
Alconja

Reputation: 14873

Use:

<%= Url.Action("Delete", "Delete", new { id = item.Mail_ID }) %>

to generate just the actual url (without the <a href="..." >...</a>). That way you can just render that into your javascript & use window.location, so your javascript becomes (assuming that function at the end of your jConfirm is the call back on acceptance):

$("a.delete").click(function() {
    var name = $(this).parent().prev('td').prev('td').text();
    jConfirm('Are you sure you want to delete the following member:' + name, 'Member Delete', function(r) {
        window.location = <%= Url.Action("Delete", "Delete", new { id = item.Mail_ID }) %>;
    });
});

Another alternative, which would mean that it would still work (sans the confirmation) if they didn't have javascript enabled would be to leave the link as it is & then do this:

$("a.delete").click(function() {
    var url = $(this).attr("href");
    var name = $(this).parent().prev('td').prev('td').text();
    jConfirm('Are you sure you want to delete the following member:' + name, 'Member Delete', function(r) {
        window.location = url;
    });
});

which grabs the url directly from the link (i.e. the one generated by your original <%= Html.ActionLink...).

Upvotes: 2

Related Questions