0

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.

norbert
  • 335
  • 1
  • 7
  • 19
  • This is C#, but .Net 2 so easily converted. It's also overkill for 1 variable, but if you have more or need to reference .Net controls in JS regularly, I'd recommend this... http://johncmolyneux.blogspot.co.uk/2012/11/reference-aspnet-control-in-javascript.html – Reinstate Monica Cellio Apr 23 '13 at 21:02

2 Answers2

1

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)

Community
  • 1
  • 1
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

You cannot do that when you're calling the webmethod through AJAX.

If you make a call through AJAX you cannot access your web form controls because you're not actually requesting the page, you're just calling the method.

Instead, you should find the label with jQuery and update it through Javascript:

function GetStockLevel() {
$.ajax({
    type: 'POST',
    url: 'Stock.aspx/StockLevel',
    // data: '{ }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'text',
    success: function (data) {
        $("#<%=stockLabel.ClientID %>").text(data);  // this only works if the javascript is in your .aspx-file
    }
});
}

If the script is not inside your .aspx, you need to find another way of finding the node on the client (by using a specific class for example).

Kenneth
  • 28,294
  • 6
  • 61
  • 84