[英]How to dynamically make a JSON object from code behind in c#
我想使用JSON對象制作流程圖
HTML
var chart = null;
$(document).ready(function(){
chart = new FlowChart($);
var chartJSON = {
nodes: [
{ id: 'p1', type: 'simple-node', left: 120 ,top:2200 , content:'Process 1'},
{ id: 'p2', type: 'simple-node', left: 120,top: 2400,content:'Process 2' },
{ id: 'p3', type: 'simple-node', left: 120, top: 2600,content:'Process 3'}
],
connections: [
{ start: 'p1', end: 'p2' },
{ start: 'p2', end: 'p3' },
]
};
chart.importChart(chartJSON);
這樣會在頁面上創建流程圖
但是我需要根據sql查詢結果動態地從后面的代碼中填充此json,我是javascript新手,無法找到解決方案的確切方向。
是的,我們可以選擇使用javascript seralize和desearlize選項動態地傳遞給后面的代碼。
例如:
result = JSON.stringify(p)// from client side it serialize json object
var a =new JavaScriptSerializer().Deserialize<class>(result) // server side seralize
注意使用system.web.serialization或newtonsoftjson dll的
詳細的答案可能會有所幫助
創建類似的類
public class connections
{
public string start { get; set; }
public string end { get; set; }
}
public class chartItem
{
public string id { get; set; }
public string type { get; set; }
public int left { get; set; }
public int top { get; set; }
public string content { get; set; }
}
// holding both chartItems and nodes
public class ChartJson
{
public List<connections> connections { get; set; }
public List<chartItem> nodes { get; set; }
}
我正在使用WebApiController,也可以使用PageMethods
public class ChartController : ApiController
{
public ChartJson Get()
{
ChartJson chartJson = new ChartJson();
chartJson.nodes = getNodes(); //function to get data from database
chartJson.connections = getConnections(); //function to get data from database
return chartJson;
}
}
在.aspx頁上
在.aspx頁面上,使用下面的jQuery調用函數
$(function () {
$.getJSON("api/Chart/Get", function (result) {
console.log(result.connections); //Check results and bind with your chart object
console.log(result.nodes); //Check results and bind with your chart object
})
});
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.