处理此jquery ajax请求的web方法的正确签名是什么?

时间:2011-09-16 16:51:55

标签: jquery asp.net ajax webmethod

我的webmethod需要什么签名才能传递'paramlist'作为参数?

<script type="text/javascript">
    $(document).ready(function () {
        var slider = $('.slider').slider({
            range: "min",
            min: 0,
            max: 100,
            change: function (e, ui) {
                var set = new Array();

                var values = $('.slider').each(function () {
                    var s = $(this);
                    var data = {
                        Name: s.attr('itemName'),
                        SelectedIndex: s.slider("option","value"),
                        Description: "this is the description",
                        CalculatedValue: 0
                    }

                    set.push(data);    
                });

                CallPageMethod("SliderChanged", set, successful, failure);
            },
            slide: function (e, ui) {
                var point = ui.value;
                $("#selected_value").html(point);
                // var width = 100 - point;
                // $("#range").css({ "width": point + "%" });
            }
        });

        function CallPageMethod(methodName, paramArray, onSuccess, onFail) {
            //get the current location
            var loc = window.location.href;
            loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;

            //call the page method
            $.ajax({
                type: "POST",
                url: loc + "/" + methodName,
                data:  JSON.stringify(paramArray),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: onSuccess,
                fail: onFail
            });
        }

        function successful(response) {
            var lbl = $('#<%= Label1.ClientID %>')
            lbl.html("Your report is now ready for download.");
            alert(response.d);
        }

        function failure(response) {
            alert("An error occurred.");
        }
    });
</script> 

我试过了:

[WebMethod]
public static string SliderChanged(MyModel[] values)
{
    return "success";
}

其中

public class MyModel
{
   public string Name {get;set;}
   public string Description {get;set;}
   public int SelectedIndex{get;set;}
   public int CalculatedValue(get;set;}
}

它失败了。

你能发现我的错误吗?

1 个答案:

答案 0 :(得分:2)

好的,让我们简化,因为那些字符串连接只是丑陋。一旦在服务器上复制相同的结构,就很容易实现这一点。

因此,假设您要将以下javascript对象发送到服务器:

var myObject = { a: { one: 1, two: 2 }, b: [1, 2, 3] };

您将定义与此签名匹配的类:

public class MyModel
{
    public Foo A { get; set; }
    public int[] B { get; set; }
}

public class Foo
{
    public int One { get; set; }
    public int Two { get; set; }
}

并有一个webmethod:

[WebMethod]
public string SomeMethod(MyModel model)
{
    ...
}

你会这样调用:

var myObject = { a: { one: 1, two: 2 }, b: [1, 2, 3] };
$.ajax({
    url: '/SomeService.asmx/SomeMethod',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(myObject),
    success: function(result) {
        // Notice the .d property here. That's specific to ASP.NET web methods, 
        // which wrap the response using this property, like this:
        // { d: ... }
        alert(result.d);
    }
});

注意JSON.stringify方法。它将javascript对象转换为JSON字符串表示形式。此方法本身内置于现代Web浏览器中,但如果您需要支持旧版浏览器,则可以在页面中包含json2.js,以测试浏览器是否本机支持该方法并使用它,或者它是否提供替代方法实施

另一个例子,如果你想发送一个对象数组,如下所示:

var myObject = [
    { a: { one: 1, two: 2 }, b: [1, 2, 3] },
    { a: { one: 5, two: 9 }, b: [7, 3, 4] },
    { a: { one: 3, two: 0 }, b: [3, 9, 3] },
]

然后您的网络方法将如下所示:

[WebMethod]
public string SomeMethod(MyModel[] model)
{
    ...
}

有了这些知识,您可以非常轻松地在javascript和Web方法之间交换数据结构。