【问题标题】:How to use Ajax with Multi Array Objects by JSON from client to server side (C#)如何通过 JSON 从客户端到服务器端使用 Ajax 和多数组对象(C#)
【发布时间】:2019-01-10 00:52:40
【问题描述】:

我该如何处理以下问题?
1、前端站点问题是如何将Object-Array转成JSON?
2.后端站点的问题是如何从前端获取JSON数据?

问题一:

如何在AJAX中做数据参数?

 var vItems = [];
        var vItem = new Item('1', '11');
        vItems.push(vItem);
        vItem = new Item('2', '22');
        vItems.push(vItem);    

 function Item(Key,Val) {
        this.Key = Key;
        this.Val = Val;
    }

 $.ajax({
            type: "POST",
            url: ".............",
            data: ????????????????????  ,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.d);  
            },
            failure: function (response) {
                alert(response.d);
            }
        });

问题2:

如何使用 C# 函数制作正确的参数

 [System.Web.Services.WebMethod]
 public static string xxx(?????????)
 {    
        return "";
 }     
 public class VItems
 {
        public string Key;
        public string Val;
 }

PS:请我在前端和后端之间使用相同的类,就像

正面

         function Item(Key,Val) {
                     this.Key = Key;
                     this.Val = Val;
                 }

背面

         public class VItems {
                     public string Key;
                     public string Val;
                 }

顺便说一句,这个问题不是重复的 URL 因为它只是一个数组对象,我需要处理多个 数据

【问题讨论】:

  • @Liam 我以前见过,但是它只是针对一个数组对象,我需要处理多个数组对象
  • @Liam 非常感谢您的帮助,我不确定如何将两个数组 Json 发送到服务器端(不正确的 JSON.stringify( vItems ))以及如何从客户端获取数据(不正确的公共静态字符串 xxx(VItems Items) )
  • @Liam 再次感谢,你给了我很多很棒的信息,现在我已经尝试解决了我的问题,和你的回答有点不同

标签: javascript c# jquery json ajax


【解决方案1】:

我已经解决了我的问题,希望它可以帮助任何有同样问题的人

var vItems = [];
        var vItem = new Item('1', '11');
        vItems.push(vItem);
        vItem = new Item('2', '22');
        vItems.push(vItem);


$.ajax({
            type: "POST",
            url: "xxxxx.aspx/xxx",
            data: JSON.stringify({ Items: vItems } )  ,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
                success: function (response) {                        
            },
            failure: function (response) {
                alert(response.d);
            }
        });

      [WebMethod]
        public static string xxx(List<VItems> Items)
        {    
            return "";
        }

        public class VItems
        {
            public string Key;
            public string Val;
        }

【讨论】:

  • @Liam 再次感谢,你给了我很多很棒的信息,现在我已经尝试解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2013-11-16
  • 2020-02-28
  • 1970-01-01
  • 2021-09-25
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
相关资源
最近更新 更多