2

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"
                            })%>

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

If you are interested, I've got a full example on how wire the click event of the link with jQuery (as Darin is suggested) in my blog: hectorcorrea.com/Blog/…
The above mentioned solution of ActionLink + jQuery is not working with me. It always navigate to the page and jQuery doesn't handle it properly. Any guess?
@Zohaib, in my original answer I forgot to cancel the default action of the link by returning false from the click callback. I've updated it to fix the problem.
0

You need to change the code:

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

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.