2012-02-13 39 views
1

我想知道如何使用JSON将数据从jquery传递到Web服务?与JSON传递数据到ASP.Net webservice

我的意思是什么样的数据类型的我应该作为输入使用的web服务,如果阵列的长度被动态地改变所有的时间例如路线串行和登机位置的数目的数目的路径,下面是一个这个例子。

{ "route": [ 
    { 
     "serial": { 
     "name": " ", 
     "rsn": " ", 
     "boardingzone": { 
          "zone": [ 
           { "name": " ", "time": " ", "qouta": " " }, 
           { "name": " ", "time": " ", "qouta": " " }, 
           { "name": " ", "time": " ", "qouta": " " } 
            ] 
      }, 
     "destination": { 
          "zone": [ 
           { "name": " " }, 
           { "name": " " }, 
           { "name": " " } 
         ] 
      } 
    } 
} 
] } 

此外,我想知道是什么样的格式是asp.net期待,这样我就可以纠正我相应的编码,谢谢您的任何意见和答复。

回答

0

我意识到前一段时间被问及这个问题,并且在ASP.Net中有很多方法可以解决这个问题。我通常所做的就是在aspx页面上使用WebMethods。您也可以使用asmx Web Services文件 - 罗伯特做得很好解释here

对于类似于上述结构的东西,我使用C#中的泛型和结构来更容易地在服务器端处理类似数据的数据在JavaScript中处理数据。也使得更容易序列化JSON。我意识到这样做有一些初始开销。我的目标是让C#能够像使用JavaScript一样在服务器端处理数据,因为它在JavaScript的前端。

我参考下列命名空间除了那些在VS2010自动添加:

using System.Collections; 
using System.Web.Services; 
using System.Web.Script; 
using System.Web.Script.Serialization; 
using System.Web.Script.Services; 

然后我定义以下结构:

public struct RouteAddedResponse { 
    public int? id; 
    public int status; 
    public string message; 
} 

public struct BoardingZoneDetail 
{ 
    public string name; 
    public string time; 
    public string quota; 
} 

public struct DestinationZoneDetail 
{ 
    public string name; 
} 

public struct RouteSerial 
{ 
    public string name; 
    public string rsn; 
    public Dictionary<string, List<BoardingZoneDetail>> boardingzone; 
    public Dictionary<string, List<DestinationZoneDetail>> destination; 
} 

下面是一个例子的ScriptMethod

// WebMethod expects: Dictionary<string, List<Dictionary<string, RoutSerial>>>; 
// Change UseHttpGet to false to send data via HTTP GET. 
[System.Web.Services.WebMethod()] 
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = false)] 
public static RouteAddedResponse AddRouteData(List<Dictionary<string, RouteSerial>> route) 
{ 
    // Iterate through the list... 
    foreach (Dictionary<string, RouteSerial> drs in route) { 

     foreach (KeyValuePair<string,RouteSerial> rs in drs) 
     { 
      // Process the routes & data here.. 
      // Route Key: 
      // rs.Key; 
      // Route Data/Value: 
      // rs.Value; 
      // ... 
     } 

    } 

    return new RouteAddedResponse() { id = -1, status = 0, message = "your message here" }; 
} 

脚本方法AddRouteData期待上面通过HTTP POST列出的结构。如果您要使用GET GET请求,则方法参数将是查询字符串变量。

注意事项

在使用ScriptMethods与ASP.Net,你需要确保Content-Type头被设置为:无论您是使用GET或POST请求application/json; charset=utf-8

希望有帮助!

+0

很好解释,但我使用Json.NET Libary进行管理,因为我的学校沙箱服务器不允许我安装任何更新或补丁。但我想不出为什么我不首先使用php的原因......哈哈 – Fy2C 2012-10-04 09:39:51