I have following the Ajax call method and The asp.net web method.
My asp.net function is returning some values I need those back in Ajax call.
I have tried a lot of things but not succeeded yet.
here is my function, I need to convert my list to 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);
});
});
here is my source code, i us webforms Application and orgchart.js liberary
this aspx.cs source code:
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);
}
}
}
and this is my aspc code
<%@ 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>
2
Answers
First you should make function
static
and addWebMethod
attribute:Then you don’t need to convert response to JSON beacuse data is already JSON. You can directly use it as following:
In addition url must be
WebForm1.aspx/ReadData
instead ofWebForm1.aspx.cs/ReadData
Change the method’s return type to JsonResult and return new Json object with subject and desription.
Jquery: