Jquery asp.net Button Click Event via ajax

后端 未结 5 793
情话喂你
情话喂你 2020-12-12 17:13

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 t

5条回答
  •  失恋的感觉
    2020-12-12 18:03

    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.

提交回复
热议问题