Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the html.actionlink using jquery

I want to call the 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") %>
like image 243
Mr A Avatar asked Jul 14 '11 09:07

Mr A


1 Answers

You don't call an actionlink using jQuery. You could send an AJAX request to the controller action this link is pointing to. If this is what you want, here's how to achieve it:

$(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 you provide a correct id (paycheck) to your action link when generating it

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

But if it is only a matter of checking whether the user accepted the terms and conditions and then perform a standard redirect to the controller action without any AJAX, simply 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;
    });
});
like image 123
Darin Dimitrov Avatar answered Nov 14 '22 22:11

Darin Dimitrov