Unlimited classification and addition, deletion, and modification of tree structure data [DEMO download] And treedemo

Source: Internet
Author: User

Unlimited classification and addition, deletion, and modification of tree structure data [DEMO download] And treedemo

Reading directory

• Unlimited grading
• Jstree plug-in
• Demo
• Create a Region object
• Meet the Data Object Dto of the jstree plug-in
• Data Conversion
• Initialize and obtain the converted data
• Front-end data loading
• Other operations
• Click add, delete, modify, and delete operations

Unlimited grading

In many cases, we are not sure about the level of the level relationship. In this case, we need to use an unlimited level.

When it comes to unlimited classification, it's time to call recursively. (It is said that frequent recursion is very performance-consuming.) Here we need to design a table mechanism to store infinitely hierarchical data. Of course, the following are the results of self-improvement, non-standard. Who has a better design.

In fact, it is also simple, that is, the relationship between ID and parent ID.

Similarly, the Id must be unique, and the ParenId must exist in the Id column. In this way, we can achieve unlimited classification. If we add a column of Sort sorting, it will be more perfect.

Jstree plug-in

Official Address: https://www.jstree.com/

Why use this plug-in? I personally think this function is quite powerful because there is a convenient api for us to bind data and supports adding, deleting, and modifying nodes by dragging.

Demo

The following describes how to implement infinitely hierarchical data operations based on the jstree plug-in. Take the region data operation as an example to compile the demo Code in Code First mode.

Create Region object

To work with the Node id automatically generated by the plug-in, we use the Node and ParentNode here to store the parent-child relationship (instead of the id and parentid mentioned above, but the actual effect is the same ).

/// <Summary> /// Region /// </summary> public class Region {// <summary> // primary key id /// </summary> public int Id {get; set ;}//< summary> /// Name /// </summary> public string Name {get; set ;} /// <summary> /// Node /// </summary> public string Node {get; set ;} /// <summary> /// parent node /// </summary> public string ParentNode {get; set ;}}

Meets the Data Object Dto of the jstree plug-in

To meet the data requirements of the jstree plug-in, we need to convert the above data into a tree-like data object.

/// <Summary> /// Dto /// </summary> public class RegionsTreeOutput {// <summary> /// Id /// </summary> public int regionsId {get; set ;}/// <summary >/// tree display text (corresponding to the region name) /// </summary> public string text {get; set ;} /// <summary> /// tree id (corresponding to Node) /// </summary> public string id {get; set ;} /// <summary> /// sub-node data (this attribute indicates the hierarchical relationship of the data) /// </summary> public List <RegionsTreeOutput> children {get; set ;}}

Data Conversion

# Region GetRegionTree auxiliary Method for Data initialization public RegionsTreeOutput LoadRegions (string id, List <Region> inRegions, RegionsTreeOutput outRegions) {List <Region> regions = inRegions. where (t => t. parentNode = id ). toList (); if (outRegions = null) // load the parent node {outRegions = ToTreeData (regions [0]); LoadRegions (outRegions. id, inRegions, outRegions);} else // load the subnode {outRegions. children = ToTreesData (regions); if (regions. count> 0) {for (int I = 0; I <regions. count; I ++) {LoadRegions (regions [I]. node, inRegions, outRegions. children [I]); // recursive call }}return outRegions;} public RegionsTreeOutput ToTreeData (Region region) {var treeData = new RegionsTreeOutput (); treeData. id = region. node; treeData. text = region. name; treeData. regionsId = region. id; return treeData;} public List <RegionsTreeOutput> ToTreesData (List <Region> listRegion) {var regions = new List <RegionsTreeOutput> (); for (int I = 0; I <listRegion. count; I ++) {regions. add (ToTreeData (listRegion [I]);} return regions;} # endregion

Initialize and obtain the converted data

/// <Summary> /// obtain the initialization data /// </summary> /// <returns> </returns> public JsonResult GetResultData () {TreeDbContext db = new TreeDbContext (); var regions = db. regions. where (t => true ). toList (); var regionObj = LoadRegions ("-1", regions, null); return Json (regionObj );}

The above background data is almost complete.

Front-end data loading

$ (Function () {$. post ("/Home/GetResultData", null, function (sData) {treeObj =$ ('# jstree_demo '). jstree ({//, "checkbox" 'ins ins': ["contextmenu", "dnd", "search", "state", "types", "wholerow"], 'core': {"animation": 0, "check_callback": true, 'force _ text': true, "themes": {"stripes": true }, 'data': sData}, "types": {"default": {"icon": "fa-folder icon-state-warning icon-lg "}, "file ": {"Icon": "fa-file icon-state-warning icon-lg" }}, "contextmenu": {select_node: false, show_at_node: true, items: function (o, cb) {// because multiple items need to be defined here, var actions = {} is returned through the object {}; // Add a "add" shortcut menu actions. create = {// The create here is actually a wide range of random names. The key is the action callback method "separator_before": false, // before the split line, "separator_after": true, // Create "after the split line" _ disabled ": false, // false indicates that the" Create "item can be used; true indicates You cannot use "label": "add", // The Name Of The Create item can be customized "action": function (data) {// Click Create to trigger this method, var inst = $. jstree. reference (data. reference), obj = inst. get_node (data. reference); // get the current node and get all the attributes of the current node // Add a node. If the following three lines of code are commented out, the node inst will not be added. create_node (obj, {}, "last", function (new_node) {setTimeout (function () {inst. edit (new_node) ;}, 0); // The rename method is triggered after a node is added, that is, the node can be renamed immediately after the node is created}) ;}; if (o. id! = "0001") // mask the "0001" Operation on the root node and change it to the actual id corresponding to the root node {// Add a "RENAME" shortcut menu actions. rename = {"separator_before": false, "separator_after": false, "_ disabled": false, // (this. check ("rename_node", data. reference, this. get_parent (data. reference), ""), "label": "RENAME", "action": function (data) {var inst = $. jstree. reference (data. reference), obj = inst. get_node (data. reference); inst. edit (obj) ;}/// Add a "delete" shortcut menu actions. delete = {"separator_before": false, "icon": false, "separator_after": false, "_ disabled": false, // (this. check ("delete_node", data. reference, this. get_parent (data. reference), ""), "label": "delete", "action": function (data) {var inst = $. jstree. reference (data. reference), obj = inst. get_node (data. reference); if (inst. is_selected (obj) {inst. delete_node (inst. get_selected ();} else {inst. delete_node (obj) ;}};} return actions; // right-click the returned menu item }},});});});

Other operations

// Delete the node $ ('# jstree_demo '). on ('delete _ node. jstree ', function (e, data) {var id = data. node. original. regionsId; $. ajax ({type: "get", url: "/Home/DeleteRegion? Id = "+ id, success: function (sData) {}}) ;}); // mobile node $ ('# jstree_demo '). on ('move _ node. jstree ', function (e, data) {saveRegions (data) ;}); // modify the name $ (' # jstree_demo '). on ('rename _ node. jstree ', function (e, data) {saveRegions (data) ;}); // SAVE function saveRegions (data) {var id = data. node. original. regionsId; var name = data. node. text; // The modified name // var oldName = data. old; // Original name // var pNode =$ ('# jstree_demo '). jstree (). get_node (data. node. parent ). original. regionsId; var josnData = {"Id": id, "Node": data. node. id, "ParentNode": data. node. parent, "Name": name}; $. ajax ({url: "/Home/SaveRegions", data: josnData, success: function (sData) {data. node. original. regionsId = sData; data. node. state. opened = false; // whether to expand }});}

Of course, remember to modify or delete the ID of the corresponding background object to take the RegionsId.

Use buttons to add, delete, modify, and delete

function createTree() {  var ref = $('#jstree_demo').jstree(true),  sel = ref.get_selected(); if (!sel.length) { return false; } sel = sel[0]; sel = ref.create_node(sel, { "type": "file" }); if (sel) {  ref.edit(sel); }};function renameTree() { var ref = $('#jstree_demo').jstree(true),  sel = ref.get_selected(); if (!sel.length) { return false; } sel = sel[0]; ref.edit(sel, function () {   });};function deleteTree() { var ref = $('#jstree_demo').jstree(true),  sel = ref.get_selected(); if (!sel.length) { return false; } ref.delete_node(sel);};

For details, download the source code:

Http://xiazai.jb51.net/201605/yuanma/TreeDemo (jb51.net).rar

I would like to introduce you to the infinite classification and tree structure data addition, deletion, and modification knowledge, and hope to help you!

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.