【问题标题】:$.ajax(..) and passing custom objects by ref$.ajax(..) 并通过 ref 传递自定义对象
【发布时间】:2010-12-10 15:23:45
【问题描述】:

如何使用 $.ajax(..) JSON 为自定义类/对象调用具有“通过引用参数”的 asmx webmethods?可能吗?

我的 c# 代码 -

    public class MyCustomClass{ public int MyProperty; MyCustomClass(){}}

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public Method1(ref MyCustomClass MyCustomObj)
    { MyCustomObj.MyProperty*=2; return MyCustomObj;}

我的 js/jquery 代码 -

function myCustomClass(){this.myProperty;}           
var myCustomObj = new myCustomClass();
myCustomObj.myProperty = 100;

$.ajax({
                type: "POST",
                data: "{'myCustomObj': " + JSON.stringify(myCustomObj) + "}", 
                url: "test.asmx/Method1",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    var data = response.d;
                    alert(data.MyProperty);
                },
                failure: function(msg) {
                    alert(msg);
                }
            });

如果 webmethod 的参数不是 ref,这一切都可以正常工作。 使用上面提到的 webmethod 签名,即使用 by ref 参数,我得到一个服务器错误(在使用 firebub 看到的服务器响应中) -

No parameterless constructor defined...

【问题讨论】:

    标签: asp.net jquery ajax web-services


    【解决方案1】:

    恐怕这是不支持的场景。您可以删除 ref 关键字并在方法内修改其值后将参数用作返回类型。

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public MyCustomClass Method1(MyCustomClass MyCustomObj)
    { 
        MyCustomObj.MyProperty *= 2; 
        return MyCustomObj;
    }
    

    【讨论】:

    • 谢谢达林。我已经尝试过了,它确实像你提到的那样工作。只是希望
    • @tubelight,什么不起作用?当我测试它工作正常。我能够在response.d.MyProperty 中获得更新的值。
    • 谢谢达林。我已经尝试过了,它确实像你提到的那样工作。只是希望我缺少一些东西,如果小心,它将与 by ref arg 一起使用。
    • @tubelight,抱歉我没有仔细阅读你的第一条评论 :-)
    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 2021-12-24
    • 1970-01-01
    • 2010-10-18
    • 2011-06-22
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多