我无法从json调用C#webmethod

时间:2014-04-02 16:00:48

标签: c# json string parameters webmethod

我似乎无法从javascript调用c#webmethod。似乎问题是输入代码,参数被转移到方法。

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

1 个答案:

答案 0 :(得分:0)

在你的功能中你有

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

尝试将此更改为

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

您无法进入ajax功能(它的异步位!)但您可以执行以下操作来帮助您进行调试:

function onSuccess(data) { ... }

...

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

和错误相同。然后,您可以在这些函数中设置断点,它们将会命中。