将Json对象从webMethod返回到Ajax调用



我有以下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);
});
});

这是我的源代码,我是webformsApplication和org.jslibary这个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>

首先,您应该创建函数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

将方法的返回类型更改为JsonResult,并返回带有subject和description的新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);
}
}
})
});

最新更新