Search code examples
javascriptvb.netwebmethodsessionidpagemethods

Get SessionID via WebMethod from VB.NET to JavaScript


I'm a little clueless having the following code just not working:

Code-behind:

<WebMethod(EnableSession:=True)>
Public Shared Function GetSessionID() As String
    Dim sID = HttpContext.Current.Session.SessionID
    Debug.WriteLine(sID)
    Return sID
End Function

JavaScript:

var sID;

function init() {
    sID = PageMethods.GetSessionID();
...

The sID is obviously there and shown in debug output but in JavaScript sID holds "undefined" because the function returns "undefined" when executed in Firebug console. What's going on there?


Solution

  • You need to define the OnSuccess callback of your PageMethods like this:

    var sID;
    
    function init() {
        PageMethods.GetSessionID(OnSuccess);
    }
    
    function OnSuccess(response, userContext, methodName) {
        sID = response;
        alert(sID);
    }
    

    References: