How to call html.actionlink using jquery

I want to call actionlink using jquery, below is the code:

  $("#paycheck").click(function () {

        if ($("#terms").attr("checked")) {

       //Call Html.ActionLink // This is where the html.ActionLink should be called to display another view


        } else {
            alert("Please agree to the terms and conditions.");
            return false;
        }
    });

<%: Html.ActionLink("Pay", "Index", "News") %>
+5
source share
1 answer

You do not call actionlink with jQuery. You can send an AJAX request for the controller action that this link points to. If this is what you want, here's how to achieve this:

$(function() {
    $('#paycheck').click(function () {
        if ($('#terms').is(':checked')) {
            // Send an AJAX request to the controller action this link is pointing to
            $.ajax({
                url: this.href,
                type: 'GET',
                // you can send some additional data along with the request
                data: { foo: 'bar' },
                success: function(result) {
                    // TODO: process the results returned by the controller
                }
            });
        } else {
            alert('Please agree to the terms and conditions.');
        }
        return false;
    });
});

Also make sure that you provide the correct identifier ( paycheck) to reference the action when creating it

<%= Html.ActionLink("Pay", "Index", "News", null, new { id = "paycheck" }) %>

But if it is only a matter of checking whether the user accepted the conditions and then performed the standard redirect to the controller action without any AJAX, just do this:

$(function() {
    $('#paycheck').click(function () {
        if ($('#terms').is(':checked')) {
            // by returning true you are letting the browser redirect to the link
            return true;
        }

        alert('Please agree to the terms and conditions.');
        // By returning false you stay on the same page and let the user
        // agree with the terms and conditions
        return false;
    });
});
+5
source

All Articles