基于Bootstrap的JQuery TreeView树形控件,数据支持json字符串、list集合(MVC5)<一>

BZ第一次自己写博客,心情好激动!!BZ也是小菜,本文如果有什么不对的地方,希望大神们多多指教,也希望和我一样的小菜多多学习。BZ在这里谢过各位。

BZ最近看了很多博友的有关TreeView的博客,发现很多都是WebForm、JQuery的。因为BZ使用的是MVC的原因,所以决定写一写关于MVC和Bootstrap的TreeView。

PS:基于Bootstrap的JQuery TreeView树形控件,JQuery版本为2.1.1(下载网上的基于Bootstrap的JQuery TreeView树形控件)。。。

本文支持两种方式的数据,一种为List集合,一种为json字符串。

先来介绍一下后台返回list集合(推荐使用此方法):

控制器代码如下:

public static List<TC_DictionaryInfo> DInfo = new List<TC_DictionaryInfo>();
        /// <summary>
        /// TreeView视图
        /// </summary>
        /// <returns></returns>
        public ActionResult May(string TypeCode,int parentId)
        {
            ViewBag.TypeCode = TypeCode;
            ViewBag.ParentId = parentId;
            return View();
        }
        [HttpPost]
        public ActionResult GetTreeData(string TypeCode,int parentId)
        {
            List<TC_DictionaryInfo> DInfo = dbll.GetModelList("TypeCode="+TypeCode);
            return Json(GetChildNodes(0,new NodeModel(){}, DInfo).nodes);
        }
        ///<summary>
        /// GetChildNodes方法,此方法使用递归
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public NodeModel GetChildNodes(int parentId,NodeModel childnodestr,List<TC_DictionaryInfo> DInfo)
        {
            List<TC_DictionaryInfo> DictionaryList = DInfo.Where(e => Convert.ToInt32(e.ParentId) == parentId).ToList();
            for (int i = 0; i < DictionaryList.Count; i++)
            {
                NodeModel NewNode = new NodeModel();
                NewNode.DicId = DictionaryList[i].DicId;
                NewNode.text = DictionaryList[i].DICName;
                NewNode.ParentId = DictionaryList[i].ParentId;
                childnodestr.nodes.Add(NewNode);
                GetChildNodes(NewNode.DicId, NewNode, DInfo);
            }
            return childnodestr;
        }
View Code

视图代码如下:

<script type="text/javascript">
        var typecode = @ViewBag.TypeCode;
        var parentid = @ViewBag.ParentId;
        $(function() {
            $.ajax({
                type: 'Post',
                url: '/Type/GetTreeData',
                data:{
                    TypeCode:typecode,
                    ParentId:parentid,
                },
                //data: para,
                dataType: 'json',
                async: false,
                success: function (data) {
                    var defaultData = eval(data);
                    //var defaultData = data;
                    $('#treeview4').treeview({
                        color: "#428bca",
                        data: defaultData
                    });
                },
                error: function (err) {
                    alert('不好意思,数据忘记带上了。。。');
                }
            });
</scipt>
View Code

第二种方式为后台返回json字符串这种方式(此方式为后台拼接json字符串传给前台):

BZ不建议大家采用这种方式,比较容易出错。

public ActionResult May(string TypeCode,int parentId)
        {
            ViewBag.TypeCode = TypeCode;
            ViewBag.ParentId = parentId;
            return View();
        } 
public ActionResult GetTreeData()
        {
            //创建jsondata对象
            StringBuilder jsonData = new StringBuilder();
            //拼接json字符串 开始{
            jsonData.Append("[");
            //调用GetChildNodes方法,默认传参试为0(0表示根节点菜单选项)
            jsonData.Append(GetChildNodes(0));
            //闭合Node子类数组 ]
            jsonData.Append("]");
            //返回json字符串
            return Json(jsonData.ToString());
        }
        /// <summary>
        /// GetChildNodes方法,此方法使用递归
        /// </summary>
        /// <param name = "parentId" ></ param >
        /// < returns ></ returns >
        public string GetChildNodes(int parentId)
        {
            //为DInfo赋值(DInfo承载页面所需的值(间接将值传给页面)),查询所有的数据
            List<TC_DictionaryInfo> DInfo = dbll.GetModelList("");
            //创建ChiidNodeStr变量
            StringBuilder ChildNodeStr = new StringBuilder();
            //查询符合条件的数据(ParentId=0),DictionaryList接收数据
            List<TC_DictionaryInfo> DictionaryList = DInfo.Where(e => Convert.ToInt32(e.ParentId) == parentId).ToList();
            //循环DictionaryList为TreeView所需数据分层级(即子类、父类等节点分开)
            for (int i = 0; i < DictionaryList.Count; i++)
            {
                //Nodes数组开始 {
                ChildNodeStr.Append("{");
                //实例化NewNode
                NodeModel NewNode = new NodeModel();
                //分别为字段赋值
                NewNode.DicId = DictionaryList[i].DicId;
                NewNode.text = DictionaryList[i].DICName;
                NewNode.ParentId = DictionaryList[i].ParentId;

                //将要显示的字段拼接
                ChildNodeStr.Append("text:'" + NewNode.text + "',");
                //超链接地址(此处设置为空链接#)
                ChildNodeStr.Append("href:'#parent1',");
                ChildNodeStr.Append("tags:['0']");
                //拼接完毕子类分层,去掉最后多余的符号(,)
                string ChildNodes = GetChildNodes(NewNode.DicId).Trim(',');
                //判断父类下是否有子类,如果有子类放到Nodes里,如果没有不让他显示为数组形式“[]”
                if (ChildNodes != string.Empty)
                {
                    //拼接Json字符串格式
                    ChildNodeStr.Append(",");
                    ChildNodeStr.Append("nodes:[");
                    ChildNodeStr.Append(ChildNodes);
                    ChildNodeStr.Append("]");
                }
                //结尾加上}, 
                ChildNodeStr.Append("},");
            }
            //返回Json字符串,并将,去掉
            return ChildNodeStr.ToString().Trim(',');
        }
View Code

前台代码和上面基本一致,唯一的差别在于

 var defaultData = eval(data); 

因为我们后台是拼接的json字符串的缘故,我们需要将json字符串转化为json数组(网上下载的基于Bootstrap的JQuery TreeView树形控件仅仅支持json数组),我也是费了很大的劲才找到的。使用MVC+Bootstrap开发TreeView的同学要注意!!!

另外,对于一些对性能要求比较高的人来说可能会认为前台的Ajax没有什么用处,白白做了一次前后台交互,是的,前面比较容易理解,由于时间原因(饿晕了!),下次BZ的博客中会给大家带来一种更为“无压力的方式”。

本文博客特别感谢方总、李总、张总的指点。

非常感谢各位观看本博客,BZ希望和更多的小菜一起成长,同样也希望大神的你提出建议。如果有不足之处还望各位不吝赐教!再次感谢各位!

原文地址:https://www.cnblogs.com/A-aron/p/5757930.html