简体   繁体   中英

How to dynamically make a JSON object from code behind in c#

I want to make a flowchart using a JSON object

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);

This creates a FlowChart on the page like this

在此处输入图片说明

but I need to populate this json from code behind depending on a sql query result dynamically, I am new to javascript and can't find out exact direction for the solution.

Look at the Newtonsoft json nuget package.

There is a method you can call to serialize an object into Json

eg. JsonConvert.SerializeObject(myObj);

yes we have option to pass dynamically to code behind by using javascript seralize and desearlize option.

eg:

result = JSON.stringify(p)// from client side it serialize json object

var a =new JavaScriptSerializer().Deserialize<class>(result) // server side seralize

note using system.web.serialization or newtonsoftjson dll's

A detailed answer, might be helpful

Create classes like

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; }
}

I am using WebApiController, you can also use 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;
  }

}

On .aspx page

On .aspx page, using jQuery call function below

$(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
            })
 });

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM