使用jQuery和asp.net将Json字符串构建为树状视图 [英] Build Json string to tree view using jQuery and asp.net

查看:88
本文介绍了使用jQuery和asp.net将Json字符串构建为树状视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net和ajax生成Json数据.

I am using asp.net and ajax to generate Json data.

当我尝试使用以下代码绘制树时,另一方面它不起作用 当我将其设置为静态时,代码2部分正在工作

When I am trying to draw tree using below code it's not working on other hand Code 2 section is working when I put it as static

注意:使用库treant.js

Note: using library treant.js

链接: http://fperucic.github.io/treant-js/

代码1:

$(function () {
    $.ajax({
        type: "POST",
        url: "Default.aspx/Hello",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data)
        {
            var Details = data.d;          
            if (Details != "")
            {
                var tree_design = '';
                //sessionStorage.setItem("str_data", tree_design);

                var currDepth = 0;
                var totalData = $.map(Details, function (n, i) { return i; }).length;
                var lastNodeIndex = parseInt(totalData) - 2;
                //-----------------------------------------//
                $.each(Details, function (index, item)
                {
                    if (Details[parseInt(index) + 1] === undefined || Details[parseInt(index) + 1] == null || Details[parseInt(index) + 1] == "") 
                    { 
                        //alert("undefined");
                    }
                    else
                    {
                        //console.log(index);

                        //console.log(item.Name);
                        //console.log(item.Depth);
                        //alert(item.Depth);
                        //console.log(item.Lft);
                        //-----------------------------------//
                        // Level down? (or the first)
                        if (((parseInt(item.Depth) > parseInt(currDepth)) || parseInt(index) == 0) && parseInt(item.Depth) != 0) {
                            tree_design += 'children: [';
                        }
                        //----------------------------------//
                        // Level up?
                        if (parseInt(item.Depth) < parseInt(currDepth)) {
                            tree_design += '' + '}],'.repeat(parseInt(currDepth) - parseInt(item.Depth));
                        }
                        //----------------------------------//
                        if (parseInt(item.Depth) != 0)
                        {
                            tree_design += '{ connectors: { style: { stroke: "#000000" } },';
                        }
                        //---------Print Node Text-------------//
                        tree_design += 'text: { name: "' + item.Name + '" },HTMLclass: "blue",image: "images/no_member.png",';
                        //---------------------------------------//
                        //console.log(Details[parseInt(index) + 1].Depth);
                        var nextEleDepth = Details[parseInt(index) + 1].Depth;
                        //console.log(nextEleDepth);

                        // Check if there's chidren
                        if (parseInt(index) != lastNodeIndex && (parseInt(nextEleDepth) <= parseInt(item.Depth)))
                        {
                            tree_design += '},'; // If not, close the <li>
                        }
                        //---------------------------------------//
                        // Adjust current depth
                        currDepth = parseInt(item.Depth);
                        //---------------------------------------//
                        //console.log(parseInt(index)+"=="+lastNodeIndex);
                        // Are we finished?
                        if (parseInt(index) == lastNodeIndex) {
                            //console.log("Are we finished");
                            tree_design += '' + '}],'.repeat(currDepth);
                        }
                        //------------------------------------//
                    }
                });
                //------------------Draw Tree---------------------------//
                //console.log(tree_design);

                var chart_config = {
                    chart: {
                        container: "#basic-example",
                        nodeAlign: "BOTTOM",
                        connectors: {
                            type: "step"
                        },
                        node: {
                            HTMLclass: "nodeExample1"
                        }
                    },
                    nodeStructure: {
                        tree_design
                    }
                };

                //console.log(tree_design);

                new Treant(chart_config);
                //-------------------------------------------------------//
            }
        }
    });
});

代码2:工作

     $(function () {
    $.ajax({
        type: "POST",
        url: "Default.aspx/Hello",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data)
        {
            var Details = data.d;          
            if (Details != "")
            {
                var tree_design = '';
                //sessionStorage.setItem("str_data", tree_design);

                var currDepth = 0;
                var totalData = $.map(Details, function (n, i) { return i; }).length;
                var lastNodeIndex = parseInt(totalData) - 2;
                //-----------------------------------------//
                $.each(Details, function (index, item)
                {
                    if (Details[parseInt(index) + 1] === undefined || Details[parseInt(index) + 1] == null || Details[parseInt(index) + 1] == "") 
                    { 
                        //alert("undefined");
                    }
                    else
                    {
                        //console.log(index);

                        //console.log(item.Name);
                        //console.log(item.Depth);
                        //alert(item.Depth);
                        //console.log(item.Lft);
                        //-----------------------------------//
                        // Level down? (or the first)
                        if (((parseInt(item.Depth) > parseInt(currDepth)) || parseInt(index) == 0) && parseInt(item.Depth) != 0) {
                            tree_design += 'children: [';
                        }
                        //----------------------------------//
                        // Level up?
                        if (parseInt(item.Depth) < parseInt(currDepth)) {
                            tree_design += '' + '}],'.repeat(parseInt(currDepth) - parseInt(item.Depth));
                        }
                        //----------------------------------//
                        if (parseInt(item.Depth) != 0)
                        {
                            tree_design += '{ connectors: { style: { stroke: "#000000" } },';
                        }
                        //---------Print Node Text-------------//
                        tree_design += 'text: { name: "' + item.Name + '" },HTMLclass: "blue",image: "images/no_member.png",';
                        //---------------------------------------//
                        //console.log(Details[parseInt(index) + 1].Depth);
                        var nextEleDepth = Details[parseInt(index) + 1].Depth;
                        //console.log(nextEleDepth);

                        // Check if there's chidren
                        if (parseInt(index) != lastNodeIndex && (parseInt(nextEleDepth) <= parseInt(item.Depth)))
                        {
                            tree_design += '},'; // If not, close the <li>
                        }
                        //---------------------------------------//
                        // Adjust current depth
                        currDepth = parseInt(item.Depth);
                        //---------------------------------------//
                        //console.log(parseInt(index)+"=="+lastNodeIndex);
                        // Are we finished?
                        if (parseInt(index) == lastNodeIndex) {
                            //console.log("Are we finished");
                            tree_design += '' + '}],'.repeat(currDepth);
                        }
                        //------------------------------------//
                    }
                });
                //------------------Draw Tree---------------------------//
                //console.log(tree_design);

                var chart_config = {
                    chart: {
                        container: "#basic-example",
                        nodeAlign: "BOTTOM",
                        connectors: {
                            type: "step"
                        },
                        node: {
                            HTMLclass: "nodeExample1"
                        }
                    },
                    nodeStructure: {
                        text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]
                    }
                };

                //console.log(tree_design);

                new Treant(chart_config);
                //-------------------------------------------------------//
            }
        }
    });
}); 

代码3:服务器脚本(ASP.Net C#)

Code-3: Server Scripting (ASP.Net C#)

using CDB.System.Common.Layout.Company;
using PRP.PPL.System.include.config.connection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PPL.Data.HRD.Organogram.Tree1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static Details[] Hello()
        {
            string sql;
            db_ppl Connstring = new db_ppl();
            sql = @"SELECT        node.category_id, node.name, COUNT(parent.category_id) - 1 AS depth, node.lft, node.rgt
                   FROM            nested_category AS node CROSS JOIN
                                            nested_category AS parent
                   WHERE        (node.lft BETWEEN parent.lft AND parent.rgt)
                   GROUP BY node.category_id, node.name, node.lft, node.rgt
                    ORDER BY node.lft";
            List<Details> details_data = new List<Details>();

            using (SqlConnection con = Connstring.getcon)
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        Details col_data = new Details();
                        col_data.category_id = reader.GetInt32(0);
                        col_data.Name = reader.GetString(1);
                        col_data.Depth = reader.GetInt32(2);
                        col_data.Lft = reader.GetInt32(3);
                        col_data.Rgt = reader.GetInt32(4);                       
                        details_data.Add(col_data);
                    }
                }
            }

            return details_data.ToArray();
        }

        //---------------For Details Data----------------//
        public class Details
        {
            public Int32 category_id { get; set; }
            public string Name { get; set; }
            public Int32 Depth { get; set; }
            public Int32 Lft { get; set; }
            public Int32 Rgt { get; set; }           

        }
    }
}

代码4:asp.Net部件

Code-4: asp.Net Part

<%@ Page Title="" Language="C#" MasterPageFile="~/CDB/System/Common/Layout/Master/Panel.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="PPL.Data.HRD.Organogram.Tree1._default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
    #basic-example
    {
        overflow: unset !important;
    }
</style>
<link href="../../../../../CDB/System/Assets/plugins/Organogram/Treant.css" rel="stylesheet" />
<link href="../../../../../CDB/System/Assets/plugins/Organogram/basic-example.css" rel="stylesheet" />

<script src="../../../../../CDB/System/Assets/plugins/Organogram/raphael.js"></script>
<script src="../../../../../CDB/System/Assets/plugins/Organogram/Treant.js"></script>

<script src="default.js"></script>
<div class="content-wrapper" style="padding:0;margin:0;">
    <!-- Main content -->
    <section class="content">
        <div class="row">           
            <!-- left column -->
            <div class="col-md-12">
                <!-- general form elements -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">Book Progress</h3>
                    </div>
                    <!-- /.box-header -->
                    <div class="box-body">

                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-group" style="overflow:scroll;">
                                    <div class="chart" id="basic-example"></div>
                                </div>
                            </div>
                        </div>
                        <div class="box-footer">

                        </div>                                                                                              
                    </div>                       
                </div>
                <!-- /.box -->
            </div>
        </div>
    </section>
 </div>
</asp:Content>

输出:

推荐答案

var tree_design='text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; 



 nodeStructure: {                       
    tree_design
}

当您在nodeStructure中链接tree_design时,它为字符串格式,但是nodeStructure期望为json格式 要么在json中转换tree_design,要么这样做

when you link tree_design in nodeStructure it's in string format but nodeStructure expect in json format either convert tree_design in json or do this way

var tree_design='{ name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; 

nodeStructure: {                       
    text: tree_design
}

这篇关于使用jQuery和asp.net将Json字符串构建为树状视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆