$ .ajax(..)并通过ref传递自定义对象

时间:2010-12-10 15:23:45

标签: asp.net jquery ajax web-services

如何使用$ .ajax(..)JSON调用自定义类/对象的'by ref arguments'的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...

1 个答案:

答案 0 :(得分:1)

我担心这是一个不受支持的情况。您可以删除ref关键字,并在方法中修改其值后将参数用作返回类型。

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