Calling VB.NET WebMethod Function from Javascript

user724198 picture user724198 · Jul 12, 2011 · Viewed 23.1k times · Source

I have a VB.NET function which looks like this:

<WebMethod()> _
Public Shared Function AuthenticateUser(ByVal UserInfo As String, ByVal Password As String) As Boolean
    Dim UserName As String

    'Just in case
    AuthenticateUser = False

    'Extract the user name from the user info cookie string
    UserName = Globals.GetValueFromVBCookie("UserName", UserInfo)

    'Now validate the user
    If Globals.ValidateActiveDirectoryLogin("Backoffice", UserName, Password) Then
        AuthenticateUser = True
    End If

End Function

I'm trying to call it from javascript like this:

function DeleteBatchJS()
{if (confirm("Delete the ENTIRE batch and all of its contents? ALL work will be lost."))
     var authenticated = PageMethods.AuthenticateUser(get_cookie("UserInfo"), prompt("Please enter your password"))
     if (authenticated == true)
           {{var completed = PageMethods.DeleteBatchJSWM(get_cookie("UserInfo"));
            window.location = "BatchOperations.aspx";
            alert("Batch Deleted.");}}}

It calls the function, but won't return a value. When walking through the code, my VB function does fire (it will return true so long as the correct password is typed in), but the javascript 'authenticated' value remains 'undefined'. It's like you can't return values from VB functions to javascript.

I also tried

if PageMethods.AuthenticateUser("UserName", "Password")
   {
     //Stuff
   }

But still no luck.

What am I doing wrong?

Thanks,

Jason

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 12, 2011

Web methods are invoked using AJAX, i.e. asynchronously, i.e. you have to wait until the method completes before consuming the results, i.e. you have to use the success callbacks:

function DeleteBatchJS() {
    var shouldDelete = confirm('Delete the ENTIRE batch and all of its contents? ALL work will be lost.');
    if (!shouldDelete) {
        return;
    }

    var password = prompt('Please enter your password');
    var userInfo = get_cookie('UserInfo');
    PageMethods.AuthenticateUser(
        userInfo, 
        password,
        function(result) {
            // It's inside this callback that you have the result
            if (result) {
                PageMethods.DeleteBatchJSWM(
                    userInfo,
                    function(data) {
                        // It's inside this callback that you know if
                        // the batch was deleted or not
                        alert('Batch Deleted.');
                        window.location.href = 'BatchOperations.aspx';
                    }
                );
            }
        }    
    );
}