Question

I can't seem to invoke the c# webmethod from javascript. It seems that the problem is enter code herewith the parameters being transfered to the method.

C# webmethod:

//a method that invokes authentication
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Login(string UserName, string Password)
{
    string result = null;
    JavaScriptSerializer jsonSer = new JavaScriptSerializer();
    try
    {
        TblUser LoginUser = new TblUser();
        bool ans = LoginUser.Login(UserName, Password);
        result = jsonSer.Serialize(ans.ToString());
        return result;
    }
    catch
    {
        result = jsonSer.Serialize("noUser");
        return result;
    }
} 

javascript:

//a function that grabs username and password
function ClientSideLogin() {
    var UserName = $('#_txtUsername').val();
    var Password = $('#_txtPassword').val();
    Login(UserName, Password);
}
//a function to authenticate from client side    
function Login(_UserName, _Password) {
        // build a datastring in JSON 
        // only a string type should be passed with paranthesis
        $(function () {
            $.ajax({ // ajax call starts
                url: 'WebServices.asmx/Login',   // server side method
                data: '{UserName:' + '"' + _UserName + '"' + ',Password:' + '"' + _Password + '"' + '}',    // the parameters sent to the server
                type: 'POST',
                dataType: 'JSON', // Choosing a JSON datatype
                contentType: "application/json; charset=utf-8",
                success: function (data) // Variable data contains the data we get from serverside
                {
                    if (data.hasOwnProperty('d')) {
                        resutls = $.parseJSON(data.d); // parse the answer to json format
                    }
                    else {
                        resutls = $.parseJSON(data);
                    }
                    var resObj = document.getElementById('result');
                    resObj.innerHTML = resutls;
                }, // end of success
                error: function (e) { // handle code in case of error
                    alert("קרתה תקלה בשרת, אנא נסה שוב מאוחר יותר" + e.responseText);
                } // end of error
            }) // end of ajax call
        });
    }
Was it helpful?

Solution

In your function you have

function Login(_UserName, _Password) {
    $(function () {
        $.ajax({ // ...

Try changing this to simply

function Login(_UserName, _Password) {
    $.ajax({ // ...

You can't step into the ajax function (that's the async bit of it!) but you can do the following to help you debug:

function onSuccess(data) { ... }

...

$.ajax({
    ...
    success: onSuccess,
    ...
});

and the same for error. You can then set breakpoints within these functions and they will hit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top