javascriptajaxvb.netscriptmanager

How to call .NET page method using VB.NET and AJAX


In my web page, I have the following JavaScript..

    function doLogin() {
        var u = document.getElementById('username').value;
        var p = document.getElementById('password').value;
        var result = PageMethods.Login(u, p, doLoginSuccess, doLoginFailed);
    }

    function doLoginSuccess(response, userContext, methodName) {
        alert('Login successful.');
    }

    function doLoginFailed(response, userContext, methodName) {
        alert('Login failed.')
    }

...and a button to call the doLogin() method:

<button onclick="doLogin()">Log In</button>

In the codebheind, I have the following vb.NET:

<System.Web.Services.WebMethod()>
Public Shared Function Login(Username As String, Password As String)
    If UserValidate(Username, Password) Then
        Return True
    Else
        Return False
    End If
End Function

Stepping through code, I can see that my .NET method is called and returning False (as expected for my test case). However, the doLoginFailed() Javascript method does not execute. Instead, the page just reloads and the input boxes for name and password get cleared. I would expect either the doLoginSuccess() or doLoginFailed() methods to execute.

I have tried having the Login() method just return True, but the behavior does not change.

This is the login page for a web application using Forms authentication, if that matters.

What am I missing?


Solution

  • I'm pretty sure webmethod only takes one callback, so you have to check the response to determine success or failure

    function doLogin() {
        var u = document.getElementById('username').value;
        var p = document.getElementById('password').value;
        var result = PageMethods.Login(u, p, doLoginCallback);
    }
    
    function doLoginCallback(response, userContext, methodName) {
        if (response)
            alert('Login successful.');
        else
            alert('Login failed.');
    }