Question

I have the following ajax.actionlink. i want to add click event to this actionlink. How can i do that

<%= Ajax.ActionLink("text", "textaction", new { param = 1}, new AjaxOptions
                            {                                   
                                OnSuccess = "updatePlaceholder",                                
                                UpdateTargetId = "result"
                            })%>
Was it helpful?

Solution

The click event handler is already added to this link because you are using the Ajax.ActionLink helper method. This click event handler will cancel the default action and send an AJAX request to the address this link is pointing to. You may try setting the OnBegin option.

And if you use jquery in your project you could have a normal link (without all the javascript added to your markup by the Ajax.ActionLink helper):

<%= Html.ActionLink(
    "text", 
    "textaction",
    new { param = 1 },
    new { id = "mylink" })
%>

and then in a separate javascript file attach the click event handler:

$(function() {
    $('#mylink').click(function() {
        // here you could execute some custom code
        // before sending the AJAX request
        $('#result').load(this.href, function() {
            // success function
        });
        return false;
    });
});

This way will achieve a clear separation between your markup and javascript files. As javascript will be in separate files which will be cached by client browser you will reduce bandwidth.

OTHER TIPS

You need to change the code:

$('#mylink').click(function(e) { e.preventDefault(); ....do what ever you want

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top