【问题标题】:Return Json object from webMethod to Ajax call从 webMethod 返回 Json 对象到 Ajax 调用
【发布时间】:2020-02-21 10:15:27
【问题描述】:

我有以下Ajax调用方法和asp.net web方法。

我的 asp.net 函数正在返回一些值,我在 Ajax 调用中需要这些值。

我尝试了很多东西,但还没有成功。

这是我的函数,我需要将我的列表转换为 JSON:

public List < Node > ReadData() {
  SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
  string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
  List < Node > list = new List < Node > ();

  SqlCommand cmd = new SqlCommand(query, conn);
  conn.Open();
  SqlDataReader dataReader = cmd.ExecuteReader();
  while (dataReader.Read()) {
    list.Add(new Node {
      uo = dataReader.GetString(0),
        uo_rattachement = dataReader.GetString(1),
        lib_reduit = dataReader.GetString(2)
    });
  }
  dataReader.Close();
  conn.Close();

  return list;

}

**Jquery:**

  $(function() {

      $.ajax({
          type: "POST",
          url: 'WebForm1.aspx.cs/ReadData',
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          success: function(response) {
            if (response != null && response.d != null) {
              var data = response.d;
              alert(typeof(data));
              data = $.parseJSON(data);
              alert(data.subject);
              alert(data.description);
            }
          }
        }; $.ajax(options);
      });
  });

这是我的源代码,我使用 webforms 应用程序和 orgchart.js 库 这个 aspx.cs 源代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace testProjet
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private object JsonConvert;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (Session["Nodes"] == null)
                {

                    var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();

                    List<Node> list = new List<Node>();
                     list.Add(new Node
                     {
                         uo = "1",
                         lib_reduit = "Name 1"
                     });



                    Session["Nodes"] = jsonSerialization.Serialize(list);

        }
            }
        }

        public static List<Node> ReadData()
        {
            SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
            string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
            List<Node> list = new List<Node>();

                SqlCommand cmd = new SqlCommand(query, conn);
                conn.Open();
                SqlDataReader dataReader = cmd.ExecuteReader();
                while (dataReader.Read())
                {
                    list.Add(new Node
                    {
                        uo = dataReader.GetString(0),
                        uo_rattachement = dataReader.GetString(1),
                        lib_reduit = dataReader.GetString(2)
                    });
                }
                dataReader.Close();
                conn.Close();

            return list;

        }
        public static void Add(string uo, string uo_rattachement, string lib_reduit)
        {
            var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
            var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
            list.Add(new Node
            {
                uo = uo,
                uo_rattachement = uo_rattachement,
                lib_reduit = lib_reduit
            });
            HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
        }

        public static void Remove(string uo)
        {
            var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
            var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
            Node removeItem = null;
            foreach (var item in list)
            {
                if (item.uo == uo)
                {
                    removeItem = item;
                    break;
                }
            }
            list.Remove(removeItem);
            HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
        }

        public static void Update(Node oldNode, Node newNode)
        {
            var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
            var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
            foreach (var item in list)
            {
                if (item.uo == newNode.uo)
                {
                    item.uo_rattachement = newNode.uo_rattachement;
                    item.lib_reduit = newNode.lib_reduit;
                    break;
                }
            }
            HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
        }


    }
}

这是我的 aspc 代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="testProjet.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width" />
    <title> OrgChart</title>
    <script src="OrgChart.js"></script>
     <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
     <style>
        html, body {
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
            overflow: hidden;
        }

        #tree {
            width: 100%;
            height: 100%;
        }

        .field_0 {
            font-family: Impact;
        }


    </style>


</head>
<body>



        <form id="form1" runat="server">
            <asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
            <div id="tree">
            </div>
            </form>

            <script >
                var chart = new OrgChart(document.getElementById("tree"), {
                    nodeBinding: {
                        field_0: "UO",
                        field_1:"Uo_Rattachement"
                    },
                    menu: {
                        pdf: { text: "Export PDF" },
                        png: { text: "Export PNG" },
                        svg: { text: "Export SVG" },
                        csv: { text: "Export CSV" }
                    },
                    nodeContextMenu: {
                        edit: { text: "Edit", icon: OrgChart.icon.edit(18, 18, '#039BE5') },
                        add: { text: "Add", icon: OrgChart.icon.add(18, 18, '#FF8304') }
                    },


                    nodeMenu: {
                        details: { text: "Details" },
                        edit: { text: "Edit" },
                        add: { text: "Add" },

                        remove: { text: "Remove" }
                    }

                });


                $.ajax({
                    type: "POST",
                    url: 'WebForm1.aspx.cs/ReadData',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        if (response != null && response.d != null) {
                            var data = response.d;//this data already json you can iterate with each
                            $.each(data, function (index, node) {
                                console.log(node);
                            });

                        }; 

                chart.on('add', function (sender, n) {
                    $.ajax({
                        type: 'POST',
                        url: '<%= ResolveUrl("WebForm1.aspx.cs/Add") %>',
                        data: JSON.stringify(n),
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json'
            });
        }); 
                chart.on('remove', function (sender, uo) {
                    $.ajax({
                        type: 'POST',
                        url: '<%= ResolveUrl("WebForm1.aspx.cs/Remove") %>',
                data: JSON.stringify({ uo: uo }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json'
            });
        });
                chart.on('update', function (sender, oldNode, newNode) {
                    $.ajax({
                        type: 'POST',
                        url: '<%= ResolveUrl("WebForm1.aspx.cs/Update") %>',
                data: JSON.stringify({ oldNode: oldNode, newNode: newNode }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json'
                    });

                });

                chart.load(<%= Session["Nodes"] %>); 



                });

    </script>



            <select style="position: absolute;right: 90px;top: 30px;color: #7a7a7a;font-size: 14px;padding: 10px;background-color: #F57C00;color: #ffffff;width: 100px;z-index:2;" id="selectTemplate">
        <option>luba</option>
        <option>olivia</option>
        <option>derek</option>
        <option>diva</option>
        <option>mila</option>
        <option>polina</option>
        <option>mery</option>
        <option>rony</option>
        <option>belinda</option>
        <option>ula</option>
        <option>ana</option>
        <option>isla</option>
        <option>deborah</option>
    </select>


</body>
</html>

【问题讨论】:

  • 你的问题是什么?你有什么错误吗?
  • data = $.parseJSON(data); 是否返回任何东西!
  • 当你从 web 方法返回列表时,你成功得到了什么响应?
  • 我需要以 orgchart 的形式显示我的数据我在生成项目时使用 orgchart.js 作为库我的页面是空的,没有节点

标签: javascript c# jquery asp.net ajax


【解决方案1】:

首先你应该创建函数static并添加WebMethod属性:

[WebMethod()]
public static List<Node> ReadData() 
{
  //..
}

那么您不需要将响应转换为 JSON,因为数据已经是 JSON。可以直接使用如下:

$.ajax({
  type: "POST",
  url: 'WebForm1.aspx/ReadData',
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  success: function(response) {
    if (response != null && response.d != null) {
       var data = response.d;//this data already is json which represent list of Node so that you can iterate with each
       $.each(data, function (index, node) {
           console.log(node);
       });
    }
  }
}; 

另外 url 必须是 WebForm1.aspx/ReadData 而不是 WebForm1.aspx.cs/ReadData

【讨论】:

  • 谢谢你 Selim,但我有一个 Web 应用程序项目,而不是核心项目???
  • 是的,这是针对 .net Web 应用程序的。你试过这个解决方案了吗?
  • 我做了,但仍然没有可显示的内容
  • 如果可能分享是的
【解决方案2】:

将方法的返回类型更改为 JsonResult 并返回带有主题和描述的新 Json 对象。

public JsonResult ReadData() {
   // Rest of your code 

   return Json(new { data = list, subject = "My subject", description = "My Description" });
}

jQuery:

  $(function () {
            $.ajax({
                type: "POST",
                url: 'Home/ReadData',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response != null && response.data != null) {
                        var data = response.data;
                        alert(typeof (data));
                        alert('subject: ' + response.subject);
                        alert('description: ' + response.description);
                    }
                }
            })
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2011-06-09
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多