2009-07-17 67 views
19

我一直在为此工作了3个小时并放弃了。 我只是简单地尝试使用jQuery将数据发送到一个asp.net web方法。 数据基本上是一堆键/值对。所以我试图创建一个数组并添加对该数组。成功发送JSON对象到asp.net WebMethod,使用jQuery

我的WebMethod(aspx.cs)看起来是这样的(这可能是错误的,我建立在JavaScript什么,我只是不知道):

[WebMethod] 
    public static string SaveRecord(List<object> items) 
    ..... 

这里是我的JavaScript示例:

var items = new Array;

var data1 = { compId: "1", formId: "531" }; 
    var data2 = { compId: "2", formId: "77" }; 
    var data3 = { compId: "3", formId: "99" }; 
    var data4 = { status: "2", statusId: "8" }; 
    var data5 = { name: "Value", value: "myValue" }; 

    items[0] = data1; 
    items[1] = data2; 
    items[2] = data3; 
    items[3] = data4; 
    items[4] = data5; 
Here is my jQuery ajax call: 

var options = { 
     error: function(msg) { 
      alert(msg.d); 
     }, 
     type: "POST", 
     url: "PackageList.aspx/SaveRecord", 
     data: { 'items': items }, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     async: false, 
     success: function(response) { 
      var results = response.d; 
     } 
    }; 
    jQuery.ajax(options); 

我得到的错误 - Invalid JSON primitive: items. -

所以...如果我这样做:

var DTO = { 'items': items };

,并设置这样的数据参数:

data: JSON.stringify(DTO)

然后我得到这个错误:

Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027 
+0

将您的web方法更改为接受普通的旧Object,然后查看该对象的具体内容,然后在Web方法中进行投射和处理。 – 2009-07-18 02:01:02

+0

虽然问题在于,您正在使用webmethods,但未使用为您自动生成的JavaScript代理类? – 2009-07-18 02:02:23

+0

感谢科里,我最初改变了网络方法接受一个普通的对象,这帮助我找出了期望。谢谢! – 29er 2009-07-20 04:21:10

回答

8

当使用AJAX.NET时,我总是使输入参数只是一个普通的旧对象,然后使用JavaScript解串器将其转换为我想要的任何类型。至少你可以通过这种方式调试并查看web方法在接收什么类型的对象。

您需要将对象转换为字符串使用jQuery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"> 
      <Scripts> 
       <asp:ScriptReference Path="~/js/jquery.js" /> 
      </Scripts> 
     </asp:ScriptManager> 
     <div></div> 
    </form> 
</body> 
</html> 
<script type="text/javascript" language="javascript"> 
    var items = [{ compId: "1", formId: "531" }, 
     { compId: "2", formId: "77" }, 
     { compId: "3", formId: "99" }, 
     { status: "2", statusId: "8" }, 
     { name: "Value", value: "myValue"}]; 

     //Using Ajax.Net Method 
     PageMethods.SubmitItems(items, 
      function(response) { var results = response.d; }, 
      function(msg) { alert(msg.d) }, 
      null); 

     //using jQuery ajax Method 
     var options = { error: function(msg) { alert(msg.d); }, 
         type: "POST", url: "WebForm1.aspx/SubmitItems", 
         data: {"items":items.toString()}, // array to string fixes it * 
         contentType: "application/json; charset=utf-8", 
         dataType: "json", 
         async: false, 
         success: function(response) { var results = response.d; } }; 
     jQuery.ajax(options); 
</script> 

而后面的代码

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Script.Serialization; 
using System.Web.Script.Services; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace CustomEquip 
{ 
    [ScriptService] 
    public partial class WebForm1 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 
     [WebMethod] 
     public static void SubmitItems(object items) 
     { 
      //break point here 
      List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items); 
     } 
    } 
} 
3

装饰你的[的WebMethod]与另一个属性:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

我相信这是在System.Web.Services.Scripting ...

+5

我认为问题不在于服务器无法将JSON发送到客户端,问题在于服务器无法对传入的JSON进行反序列化。 – SolutionYogi 2009-07-17 23:38:05

46

在您的例子时,如果你的数据参数是它应该工作:

data: "{'items':" + JSON.stringify(items) + "}" 

请记住,您需要发送一个JSON字符串到ASP.NET AJAX。如果您将实际的JSON对象指定为jQuery的数据参数,则会将其序列化为& k = v?k = v对。

看起来你已经阅读过,但再看看我的example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX。它涵盖了您做这项工作所需的一切。

注意:您不应该使用JavaScriptSerializer在“ScriptService”中手动反序列化JSON(如其他人所建议的那样)。它会根据您的方法的指定类型的参数自动为您执行此操作。如果你发现自己这样做,你做错了。

5

以下是我们项目的代码片段 - 我遇到了麻烦没有包装的对象为一个字符串,也与日期的价值观 - 希望这可以帮助别人:

 // our JSON data has to be a STRING - need to send a JSON string to ASP.NET AJAX. 
     // if we specify an actual JSON object as jQuery's data parameter, it will serialize it as ?k=v&k=v pairs instead 
     // we must also wrap the object we are sending with the name of the parameter on the server side – in this case, "invoiceLine" 
     var jsonString = "{\"invoiceLine\":" + JSON.stringify(selectedInvoiceLine) + "}"; 

     // reformat the Date values so they are deserialized properly by ASP.NET JSON Deserializer    
     jsonString = jsonString.replace(/\/Date\((-?[0-9]+)\)\//g, "\\/Date($1)\\/"); 

     $.ajax({ 
      type: "POST", 
      url: "InvoiceDetails.aspx/SaveInvoiceLineItem", 
      data: jsonString, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json" 
     }); 

服务器的方法签名是这样的:

[WebMethod] 
    public static void SaveInvoiceLineItem(InvoiceLineBO invoiceLine) 
    { 
0

这是你定义你的数据(JSON)的方式

data: { 'items': items }, 

和这个事情应该是这样

data: '{ items: " '+items +' "}', 

基本上你是序列化的参数。