刚开始接触ASP.NET的MVC3,想实现一个从数据库中取数据生成动态树的功能。
表结构是 DeptID DeptName DeptPid 正好符合jquery easyui 1.44树的格式。
我想着是类库中写一个查询,然后再控制器中实例化,再在view中调用,也不知道思路对不对,刚学.NET,见笑了
想问下如何通过json转化数据生成Jquery easyui的树?后台用LINQ写,能送上各个部分的完整的代码就好了,谢谢

解决方案 »

  1.   

    这个结构符合 easyui  tree 。
    easyui tree 的标准格式没有 pid 。
    easyui gridtree 的格式才有。你写个跟树形数据源对应的一个实体类。
     [DataContractAttribute]
        public class treenode
        {
            public treenode(string _id, string _text)
            {
                this.id = _id;
                this.text = _text;
            }
           
            [DataMember]
            public string id
            {
                get;
                set;
            }
            [DataMember]
            public string text
            {
                get;
                set;
            }
                 private CustomAttributes _attributes = new CustomAttributes();
            [DataMember]
            public CustomAttributes attributes
            {
                get
                {
                    return _attributes;
                }
                set
                {
                    _attributes = value;
                }
            }
            private List<treenode> _children = new List<treenode>();
            [DataMember]
            public List<treenode> children
            {
                get
                {
                    return _children;
                }
                set
                {
                    _children = value;
                }
            }
        }
        
        public class CustomAttributes
        {
            public string url
            {
                get;
                set;
            }
        }下级 都要添加到 children 属性里面,而不是常见的 pid 属性。实体类List 转换为 JSON 的代码在我的博客里面。现在打不开,没法贴代码。
      

  2.   

    请问没有pid怎么生成树呢?得需要父节点吧?我不太懂gridtree和tree的区别,但我记得用的是easyui树里的第一个例子,好像就叫tree吧?可能是我小白了
      

  3.   


    实体类List 转换为 JSON 的代码
    恩 ,最需要这个了,坐等
      

  4.   

    public string ObjectToJson<T>(string jsonName, IList<T> t)        {            StringBuilder Json = new StringBuilder();            Json.Append("{\"" + jsonName + "\":[");            if (t.Count > 0)            {                for (int i = 0; i < t.Count; i++)                {                    T obj = Activator.CreateInstance<T>();                    Type type = obj.GetType();                    PropertyInfo[] pis = type.GetProperties();                    Json.Append("{");                    for (int j = 0; j < pis.Length; j++)                    {                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(t[i], null) + "\"");                        if (j < pis.Length - 1)                        {                            Json.Append(",");                        }                        else                        {                            Json.Append("}");                        }                        if (i < t.Count - 1)                        {                            Json.Append(",");                        }                    }                }            }            Json.Append("]}");            return Json.ToString();        }
      

  5.   

    在Controller里/// <summary>
            /// 服务树
            /// </summary>
            /// <returns></returns>
            public ActionResult ServiceTree()
            {
                List<Service> Services = bll.GetModelList("CompanyID=" + CONST.TopCompanyID);
                ViewData["Services"] = Services;
                return View();
            }
    界面:<div class="dtree">
    <script type="text/javascript">
        d = new dTree('d');     d.add("0", "-1", '全部服务');
        <%
            foreach (var item in (IEnumerable<mry.Model.Service>)ViewData["Services"])
            {
            if(item.Pid==null)item.Pid=0;
            %>
                d.add('<%:item.ID %>', '<%:item.Pid %>', '<%:item.Name %>', "javascript:dTreeOnClick('<%:item.ID %>','<%:item.IsDir%>')");
            <% }%>
        document.write(d);
        d.openAll();
        d.config.useCookies = false;
    </script>
    </div>
      

  6.   

    我还是没太搞明白,望老师们见谅
    我的operator里是这样写得
            /// <summary>
            /// 单个查询
            /// </summary>  
           public List<OrgDept> Query(string DeptID)
            {
                NewMveProgramDBDataContext db = new NewMveProgramDBDataContext();
                var org = (from u in db.OrgDept
                           where u.DeptPid==DeptID||u.DeptID==DeptID
                           select u);
                return org.ToList();
            }
    就是传一个ID查出它和它所有子节点。
    问题一:这样写可以吗?然后想问下想把这个实例化,在controller里怎么写?问题二:还需要写这个吗?
    namespace NewMveProgram.Models {
        public class TreeNode {
            public string id { get; set; }
            public string text { get; set; }
            public string iconCls { get; set; }
            public Attributes attributes { get; set; }
            public List<TreeNode> children { get; set; }
        }    public class Attributes {
            public string url { get; set; }
            public int price { get; set; }
            public string dateType { get; set; }
        }
    }
    问题三:我看easyui给的前台是这样写得,请问怎么把前后联系起来,吧我查出来的数据变成一棵树
        $(function () {         $('#tt2').tree({
                checkbox: false,
                url: 'ListTree',
                onClick: function (node) {
                    alert('you click ' + node.text);
                }
            });
        });
      

  7.   

    我刚刚改善了一下代码,并借鉴了
    http://stackoverflow.com/questions/9409021/id-parentid-list-to-hierarchical-list
    完整如下:【MVC3测试通过】

    (Model)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;namespace MVCEmployeeBenifitEasyUI.Models
    {
        public class PowerList
        {
            [Key]
            public int ID { get; set; }
            public string text { get; set; }
            public int? parent { get; set; }        public List<PowerList> Children { get; set; }        private CustomAttributes _attributes = new CustomAttributes();
            public CustomAttributes attributes { get; set; }
        }    public class CustomAttributes 
        {
            public string url { get; set; }
        }
    }
    (Controller)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVCEmployeeBenifitEasyUI.Models;namespace MVCEmployeeBenifitEasyUI.Controllers
    {
        public class HomeController : Controller
        {
            private EmployeeBenfitsEntities db = new EmployeeBenfitsEntities();
            //
            // GET: /Home/        public ActionResult Index()
            {
                return View();
            }        public JsonResult PowerList() 
            {
                List<PowerList> items=db.PowerList.ToList();            Action<PowerList> SetChildren = null;            SetChildren = parent =>
                {
                    parent.Children = items
                        .Where(childItem => childItem.parent == parent.ID)
                        .ToList();                //Recursively call the SerChildren method for each child.
                    parent.Children.ForEach(SetChildren);            };            //Initialize the hierarchical list to root level item
                List<PowerList> hierarchicalItems = items
                    .Where(rootItem => rootItem.parent == 0)
                    .ToList();
                hierarchicalItems.ForEach(SetChildren);            return Json(hierarchicalItems, JsonRequestBehavior.AllowGet);
            }
        }
    }