Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery asp.net Button Click Event via ajax

I was wondering if anyone can point me in the right direction. I have an asp.net button with a click event (that runs some server side code). What i'd like to do is call this event via ajax and jquery. Is there any way to do this? If so, i would love some examples.

Thanks in advance

like image 636
zSynopsis Avatar asked May 13 '09 02:05

zSynopsis


2 Answers

This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:

When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.

 $(document).ready(function() {   $("input[id$='btnAwesome']").click(function() {     // Do client side button click stuff here.   }); }); 

The id$= is doing a regex match for an id ENDING with btnAwesome.

Edit:

Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.

The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.

 $.ajax({   type: "POST",   url: "PageName.aspx/MethodName",   data: "{}",   contentType: "application/json; charset=utf-8",   dataType: "json",   success: function(msg) {     // Do something interesting here.   } }); 

I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.

like image 99
Gromer Avatar answered Sep 28 '22 13:09

Gromer


I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?

To cater for that possibility, I would do the following:

$(document).ready(function() {   $('#<%=myButton.ClientID %>').click(function() {     // Do client side button click stuff here.   }); }); 

It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.

If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.

like image 21
Lucas Wilson-Richter Avatar answered Sep 28 '22 11:09

Lucas Wilson-Richter