从Javascript调用VB.NET WebMethod函数

时间:2011-07-12 18:47:12

标签: javascript asp.net vb.net pagemethods webmethod

我有一个VB.NET函数,如下所示:

<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

我正试图通过这样的javascript调用它:

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.");}}}

它调用函数,但不会返回值。在遍历代码时,我的VB函数会触发(只要键入了正确的密码,它就会返回true),但是javascript'authenticated'值仍然是'undefined'。这就像你不能将VB函数的值返回到javascript。

我也试过

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

但仍然没有运气。

我做错了什么?

谢谢,

杰森

1 个答案:

答案 0 :(得分:4)

使用AJAX调用Web方法,即异步调用,即必须等到方法完成后再使用结果,即必须使用成功回调:

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';
                    }
                );
            }
        }    
    );
}