Mvc4+easyui-based Web development Framework Experience Summary (2)-Build Web interface with Easyui tree controls

Source: Internet
Author: User
Tags tojson

Http://www.cnblogs.com/wuhuacong/p/3669575.html

Recently spent a lot of time in refactoring and further refining my web development framework, and strive to in the user experience and interface design, and WinForm development framework to maintain consistency, while on the web, I mainly use Easyui front-end Interface processing technology, take the MVC technology route, in the reconstruction process, Many details spend a lot of time on research and refinement, step by step, but also accumulated a lot of experience, this series will mainly introduce me to further improve my web framework based on the accumulated experience to share, this essay mainly introduces the use of Easyui tree control to build a web interface experience.

In many interface design, we may need to introduce a tree list control, this control can be implemented with Ztree, but also can be used Easyui built-in tree control to display, for historical reasons, I originally preferred to use Ztree, the latest changes it all to Easyui tree control, and has been improved optimization , find the code more concise and crisp, very good.

1. Using the Easyui tree control on the interface

In general, using the Easyui tree control, the code is very simple, the script code is shown below, mainly by invoking the URL to obtain the JSON data, and then can be displayed, through the onclick can be used to respond to the user click the node operation, each nodes have ID, text, ICONCLS, Checked,state,children and other properties.

1) JSON data binding for tree control

            $ (' #treeDept '). Tree ({                URL: '/user/[email protected]["UserId"] ',                onclick:function (node) {                    LoadData ( node.id);                }            );

2) collapse and expand of tree controls

The expansion and collapse of a tree control can be handled by defining two common scripts, as shown below.

        function ExpandAll (treename) {            var node = $ (' # ' + treename). Tree (' getselected ');            if (node) {                $ (' # ' + treename). Tree (' ExpandAll ', node.target);            }            else {                $ (' # ' + treename). Tree (' ExpandAll ');            }        }        function CollapseAll (treename) {            var node = $ (' # ' + treename). Tree (' getselected ');            if (node) {                $ (' # ' + treename). Tree (' CollapseAll ', node.target);            }            else {                $ (' # ' + treename). Tree (' CollapseAll ');            }        }

Then, after the page has finished loading, bind the specified button control to it, as shown in the following code.

        Initialize the object        $ (document). Ready (function () {            //Initialize the mechanism classification            Initoucategorys ();            Institutional basic Information            Initdepttreeview ();            $ ("#deptExpand"). Bind ("click", Function () {                ExpandAll ("treedept");            });            $ ("#deptCollapse"). Bind ("click", Function () {                CollapseAll ("treedept");            });                                   $ ("#loading"). Center (); Loading image Display Center        });

3) The tree control's check box displays

The tree control does not have a check box by default, and it can be displayed by the Property checkbox setting, which is the code in my project.

Where Cascadecheck the tree control cascade, the default is cascade, that is, as long as the parent control is selected, all its child controls will be selected, we can set it to false, let it not cascade, so in many cases is required.

            $ (' #treeFunctionView '). Tree ({                checkbox:true,                cascadecheck:false,                url: '/function/[email protected][') UserId "] ',                onclick:function (node) {                    //                }            });

4) Full selection and no selection of tree controls

This all do not choose the characteristics, I found a lot of articles, did not find, in fact, later found that we understand the node of the tree is biased, the realization of the implementation is also very easy.

If you cancel the selection of all nodes, the code looks like this. Its method getchecked is to return all nodes, not a node. They put all the selected nodes into a combination, not like WinForm inside, the tree node needs to be recursive query, here only need a For loop can be expanded, I here to all the selected nodes, set to uncheck the State can be implemented to cancel all tree node tick state.

        function Unchecktree (tree) {            var nodes = $ (' # ' + Tree). Tree (' getchecked ');            if (nodes) {                for (var i = 0; i < nodes.length; i++) {                    $ (' # ' + Tree). Tree (' uncheck ', nodes[i].target);                }            }        }

We know that many tree controls, for ease of operation, provide an all-or-nothing operation, which is easy to implement in the Easyui tree control. The GetChildren here is similar to the above meaning, and it also returns all the child nodes, without recursion, and with a For loop you can traverse all the nodes and the multilevel sub-nodes below them. In other words, it is a two-dimensional data, without recursive query.

        function Checkalltree (tree, checked) {            var children = $ (' # ' + Tree). Tree (' GetChildren ');            for (var i = 0; i < children.length; i++) {                if (checked) {                    $ (' # ' + Tree). Tree (' Check ', children[i].target); 
   
    } else {                    $ (' # ' + Tree). Tree (' uncheck ', Children[i].target);}}}        
   

5) The tree control class of the drop-down list

In addition to the normal tree list, there is a more special tree control, that is, in the Combotree, that is, in the drop-down list of the integrated tree control, its operation is similar to the normal tree control, a lot of event properties are the same, its use code as shown below.

        Initialize company        function Initcompany () {            $ (' #txtCompany_ID '). Combotree ({                URL: '/user/[email protected][' UserId "] ',                Valuefield: ' id ',                textField: ' text ',                required:true,                onclick:function (node) {                    //                }            });        }

2. Optimization of tree control

1) Normal JSON data generation

As we said earlier, we generally use JSON data to work with JavaScript for convenience, and the Easyui tree control supports a good JSON link binding, so we only need to implement the JSON data generation in the corresponding controller, if it is the JSON data that we want to determine initially , which is usually generated by hand, is shown in the code below.

        Public ActionResult Gettreejson () {String folder = "/content/jqueryeasyui/themes/icons/customed            /"+" organ.png ";            String leaf = "/content/jqueryeasyui/themes/icons/customed/" + "organ.png";            String json = Gettreejson ( -1, folder, leaf); JSON = JSON.            Trim (', '); Return Content (String.        Format ("[{0}]", JSON)); }///<summary>///recursion get tree information///</summary>//<param name= "PID" ></param >//<returns></returns> private string Gettreejson (int PID, string foldericon, String Leafi Con) {string condition = string.            Format ("pid={0}", PID); list<ouinfo> nodeList = Bllfactory<ou>.            Instance.find (condition);            StringBuilder content = new StringBuilder (); foreach (Ouinfo model in nodeList) {int parentid = (model. PID = =-1? 0:model.                PID); String Tempmenu = String. Format ("{{id:{0}, pid:{1}, name:\" {2}\ ", icon:\" {3}\ "}},", Model.id, ParentID, model.                Name, IMGSRC); String submenu = this.                Gettreejson (Model.id, Foldericon, Leaficon); String Parentmenu = String. Format ("{{\" "id\": {0}, \ "Pid\": {1}, \ "name\": \ "{2}\" ", Model.id, ParentID, model.                Name); if (string. IsNullOrEmpty (submenu)) {if (!string. IsNullOrEmpty (Leaficon)) {Parentmenu + = string.                    Format (", \" icon\ ": \" {0}\ "}},", Leaficon);                    } else {parentmenu + = "},"; }} else {if (!string. IsNullOrEmpty (Foldericon)) {Parentmenu + = string.                    Format (", \" icon\ ": \" {0}\ "}},", Foldericon); } else {PareNtmenu + = "},"; }} content.                Appendline (Parentmenu.trim ()); Content.            Appendline (Submenu.trim ()); } return content. ToString ().        Trim ();  }

The above code is very good implementation of the database structure based on the relationship between the generation of JSON data, but feel part of the hard coding, the data gathered out, always feel less than ideal, if we want to simplify, how to operate it?

2) Simple and beautiful JSON data generation

This section continues with the above topic to see how to simplify the generation of JSON, because we need a lot of these JSON operations, if the above method, I feel very error-prone, but also not very beautiful. To solve this problem, we can use the entity class that defines a JSON data to host the relevant information, as the following definition shows.

    <summary>////define Easyui tree data to facilitate the controller to generate JSON data for delivery///</summary> [DataContract] [Serializable ] public class Easytreedata {//<summary>///ID//</summary> [Datamembe        R] public string ID {get; set;} <summary>///Node name///</summary> [DataMember] public string text {get; set; }///<summary>//whether to expand//</summary> [DataMember] public string        State {get; set;} <summary>///Icon Style///</summary> [DataMember] public string iconcls {get; SE T }///<summary>///child node collection///</summary> [DataMember] public list<easytr                Eedata> children {get; set;} <summary>////default constructor////</summary> public easytreedata () {THIS.C Hildren = new List<EasyTreeData> ();        This.state = "open"; }///<summary>///Common constructors///</summary> public easytreedata (string ID, String te            XT, String iconcls = "", String state = "Open"): the This () {this.id = ID;            This.text = text;            This.state = State;        This.iconcls = Iconcls;  }///<summary>//////</summary> public easytreedata (int id, string text, String iconcls = "", String state = "Open"): the This () {this.id = ID.            ToString ();            This.text = text;            This.state = State;        This.iconcls = Iconcls; }    }

Then, we need to generate JSON data in the place, use this entity class to carry, and then the list to generate JSON on it, very simple, hehe.

        <summary>//////        based on user's tree JSON//</summary>//        <param name= "DeptID" > User Department </param>        //<returns></returns> public actionresult getusertreejson (int deptid)        {            list<easytreedata> treelist = new list<easytreedata> ();            Treelist.insert (0, New Easytreedata (-1, "none"));            list<userinfo> list = Bllfactory<user>. Instance.findbydept (deptid);            foreach (UserInfo info in list)            {                treelist.add (new Easytreedata (Info.id, info). FullName, "Icon-user"));            }            String json = ToJson (treelist);            Return Content (JSON);        }

If a recursive operation is required, the same approach is possible.

        <summary>///Get user's departmental tree structure (grading required)///</summary>//<param name= "UserId" >        User id</param>//<returns></returns> public actionresult getmydepttreejson (int userId)            {StringBuilder content = new StringBuilder (); UserInfo UserInfo = Bllfactory<user>.            Instance.findbyid (USERID);                if (userInfo! = null) {Ouinfo groupinfo = Getmytopgroup (UserInfo); if (groupinfo! = null) {list<ounodeinfo> List = Bllfactory<ou>.                    Instance.gettreebyid (groupinfo.id);                    Easytreedata treedata = new Easytreedata (groupinfo.id, Groupinfo.name, Geticoncls (groupinfo.category));                    Gettreedatawithounode (list, treedata); Content. Append (base.                ToJson (Treedata)); }} String json = String. Format ("[{0}]", content. ToString (). Trim (', '));            Return Content (JSON); }

The above uses Easytreedata to host the data, and then builds the list, which is itself a multi-level tree object, and then a Tojson method can transform the list object into Jason data perfectly.

The main tojson here is to invoke the operation of the JavaScriptSerializer object, as shown below.

        <summary>////        The object is a JSON string///</summary>//        <param name= "obj" > Pending serial Number Object </param >//        <returns></returns>        protected string ToJson (object obj)        {            string jsondata = (new JavaScriptSerializer ()). Serialize (obj);            return jsondata;        }

3. Tree control effect Display

After describing how to use it, let's look at the display of the tree controls in several of my scenes, so we can deepen our understanding of the use of the Easyui tree controls above.

1) The list of organizations is as follows:

2) Role Tree list display

3) feature tree list display

4) menu Tree list display

5) Login log Tree list display

6) drop-down list tree display

(EXT) Mvc4+easyui-based Web development Framework Experience Summary (2)-Build a web interface with Easyui tree controls

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.