Search code examples
javascriptjqueryasp.netwebmethod

JQuery.Ajax calling WebMethod + event handler


I have an asp.net application, one page is using JQuery.Ajax to call a WebMethod function in aspx code

// Default.aspx.cs

[WebMethod]
public static string GetCustomersCount()
{
    ...
    dbReader.OnReadAsyncComplete += (_o, _e) => { ... };
    ...
}

this function reads data from database (asynchronously) and has an event handler OnReadAsyncComplete. Now how can I access any client or server UI element (label, textbox - whatever) - to write some value in that UI element? WebMethod is static, so neither Response object nor UI Elements with runat="server" are not accessible in dbReader.OnReadAsyncComplete


Solution

  • If you want to do things that way, that's what postback-style code is for. If you're doing AJAX-style programming instead, your client-side code is where you update your page:

    $.ajax(...).then(function(data) {
        $('#your-label').text(data.someValue);
    });