Jquery – Accessing ASP control from webmethod

ajaxasp.netjqueryvb.net

I've inherited some ASP 2.0 webforms code that queries a webmethod and returns a string, a simplified version of it would be

Code Behind

<System.Web.Services.WebMethod()> _
Public Function StockLevel() as String
    return "120"
End Sub

.aspx Page

function GetStockLevel() {
$.ajax({
    type: 'POST',
    url: 'Stock.aspx/StockLevel',
    // data: '{ }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'text',
    success: function (data) {
    alert(data);
    }
});
}

The page has a asp label control on it e.g asp:Label id="stockLabel" runat="server"

Currently it returns the string 120 into the jquery call and displays the alert, when i try to modify the StockLevel function to set the label text to 120 such as

stockLabel.Text = "120"

I get intellisense, but it does not appear to update the value on the page, i guess this is due to the nature of AJAX (In which case i should just use the return value from the ajax call to set the value of the label.), and the control is probably not loaded at this point or there is a scope issue. Is this correct? I'd like to know why this happens, is this the correct behaviour i should expect or am i doing something wrong and the label should update with the correct value?

Any pointers or advice would be great.

Best Answer

I believe ASP Labels get rendered as Spans, you should be able to change it like so:

success: function (data) {
    $("#<%=stockLabel.ClientID %>").text(data);
}

As far as accessing page controls from a web method, you aren't allowed to. This post goes into it a lot better than I can: Access ASP.NET control from static [WebMethod] (JS ajax call)