【问题标题】:Calling VB.NET WebMethod Function from Javascript从 Javascript 调用 VB.NET WebMethod 函数
【发布时间】:2011-10-03 21:47:35
【问题描述】:

我有一个如下所示的 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 的“已验证”值仍然是“未定义”。就像您无法将值从 VB 函数返回到 javascript。

我也试过

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

但还是没有运气。

我做错了什么?

谢谢,

杰森

【问题讨论】:

  • 旁注,我从不提示输入这样的密码。
  • @Joel -- 密码编码是为了简单起见。真正的代码涉及更多一点

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


【解决方案1】:

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

【讨论】:

  • 也可以传入函数的地址,也可以传入错误函数
  • @Darin:我认为你错过了.d,这可能是 OP 真正的问题。
  • @naveen,不,没有.d。这是当您使用 jQuery 使用 PageMethods 时。 ASP.NET 自动生成的函数会自动删除它。
  • @Darin:它的工作时间正好是 1/2。通常在连续第 4 或第 5 次尝试后,它开始工作(4 或 5 次,当它再次开始不工作时)。
  • @Json,这可能是因为您的服务器 PageMethod 有 1/2 的时间都在抛出异常吗?您是否尝试在其中设置断点?您是否还尝试使用 FireBug 分析 AJAX 请求/响应?