0

在 WebForms 应用程序中使用 WebMethod 时,我试图绑定到一个类,但出现以下错误:

{ "Message":"Invalidwebservicecall,missingvalueforparameter:\u0027dto\u0027.", "StackTrace":"atSystem.Web.Script.Services.WebServiceMethodData.CallMethod(Objecttarget,IDictionary2parameters) atSystem.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Objecttarget,IDictionary2parameters) atSystem.Web.Script.Services.RestHandler.InvokeMethod(HttpContextcontext,WebServiceMethodDatamethodData,IDictionary`2rawParams) atSystem.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContextcontext,WebServiceMethodDatamethodData)", "ExceptionType":"System.InvalidOperationException" }

但是,如果我使用 3 个单独的字符串属性,则调用成功且没有错误。我的问题是该对象可能有 20 多个属性,我不喜欢那么长的方法签名(更不用说它们很容易改变)。

网络方法

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class FooService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<FooDTO> Test(FooDTO dto)
    {
        System.Diagnostics.Debug.Assert(dto != null, "Oops, the dto is null");
        return null;
    }
}

jQuery用来调用方法

var dto = {};
dto.Test1 = 'Ticket Number';
dto.Test2 = 'Title';
dto.Test3 = true;

$.ajax({
    url: '/service/FooService.asmx/Test',
    data: JSON.stringify(dto),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    type: 'POST',
    success: function (data) {
        alert('hooray!');
    },
    error: function (data) {
        alert('NOPE');
    }
});
4

3 回答 3

1

您应该创建另一个对象并将您的 dto 对象添加为属性。请注意,该属性应与 Web 方法中的参数同名。

var data = {};
data.dto = dto;

然后发送您的数据对象

$.ajax({
data: JSON.stringify(data),
type: 'POST',
....
于 2015-11-24T15:54:04.163 回答
0

一个参数怎么样?您可以使用像 JSON.NET 这样的库,它可以很容易地解析它并将其再次转换回对象;您需要做的就是确保它以字符串的形式传入服务器,该字符串是 JSON 内容。

于 2013-11-11T20:14:25.903 回答
0

如果您使用的是 POST 方法,请删除 JSON.stringify

$.ajax({
    data: dto,
    type: 'POST',
    ....
});
于 2013-11-12T11:16:10.490 回答