0

I have implemented a code to create Tree View and also save it into database.

Controller

        public ActionResult IndexMda()
    {
        using (BackendEntities context = new BackendEntities())
        {
            var plist = context.MDA.Where(p => p.PARENT_MDA_ID == null).Select(a => new
            {
                a.MDA_ID,
                a.MDA_NAME,
                a.MDA_DESCRIPTION,
                a.ORGANIZATION_TYPE
            }).ToList();
            ViewBag.plist = plist;
        }
        GetHierarchy();
        return View();
    }
    public JsonResult GetHierarchy()
    {
        List<MDA2> hdList;
        List<MdaViewModel> records;
        using (BackendEntities context = new BackendEntities())
        {
            hdList = context.MDA.ToList();

            records = hdList.Where(l => l.PARENT_MDA_ID == null)
                .Select(l => new MdaViewModel
                {
                    MDA_ID = l.MDA_ID,
                    text = l.MDA_NAME,
                    MDA_DESCRIPTION = l.MDA_DESCRIPTION,
                    ORGANIZATION_TYPE = l.ORGANIZATION_TYPE,
                    PARENT_MDA_ID = l.PARENT_MDA_ID,
                    children = GetChildren(hdList, l.MDA_ID)
                }).ToList();
        }

        return this.Json(records, JsonRequestBehavior.AllowGet);
        // return View();
    }

    private List<MdaViewModel> GetChildren(List<MDA2> hdList, long PARENT_MDA_ID)
    {
        return hdList.Where(l => l.PARENT_MDA_ID == PARENT_MDA_ID)
            .Select(l => new MdaViewModel
            {
                MDA_ID = l.MDA_ID,
                text = l.MDA_NAME,
                MDA_DESCRIPTION = l.MDA_DESCRIPTION,
                ORGANIZATION_TYPE = l.ORGANIZATION_TYPE,
                PARENT_MDA_ID = l.PARENT_MDA_ID,
                children = GetChildren(hdList, l.MDA_ID)
            }).ToList();
    }

    [HttpPost]
    public JsonResult ChangeNodePosition(long MDA_ID, long PARENT_MDA_ID)
    {
        using (BackendEntities context = new BackendEntities())
        {
            var Hd = context.MDA.First(l => l.MDA_ID == MDA_ID);
            Hd.PARENT_MDA_ID = PARENT_MDA_ID;
            context.SaveChanges();
        }
        return this.Json(true, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddNewNode(AddNode model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                using (BackendEntities db = new BackendEntities())
                {
                    MDA2 hierarchyDetail = new MDA2()
                    {
                        MDA_NAME = model.NodeName,
                        PARENT_MDA_ID = model.ParentName,
                        MDA_DESCRIPTION = model.NodeDescription,
                        ORGANIZATION_TYPE = model.NodeOrganizationType
                    };

                    db.MDA.Add(hierarchyDetail);
                    db.SaveChanges();
                }
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
        }

        catch (Exception ex)
        {
            throw ex;
        }

        return Json(new { success = false }, JsonRequestBehavior.AllowGet);
    }

The partial view is where the Tree View is created Partial View

@model BPP.CCSP.Admin.Web.ViewModels.AddNode

<div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
        <button type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">Add Node</h4>
    </div>
    <div class="modal-body">
        @using (Html.BeginForm("AddNewNode", "Mda", FormMethod.Post, new { @id = "formaddNode", @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

            <div class="col-md-12">

                <div class="col-md-6 row">
                    <div class="input-group">
                        <input type="text" class="form-control" value="Perent Node" readonly="readonly">
                        <span class="input-group-addon">
                            @Html.RadioButtonFor(model => model.NodeTypeRbtn, "Pn", new { @class = "btn btn-primary  rbtnnodetype" })
                        </span>

                    </div>
                </div>
                <div class="col-md-6">
                    <div class="input-group ">
                        <input type="text" class="form-control" value="Child Node" readonly="readonly">
                        <span class="input-group-addon">
                            @Html.RadioButtonFor(model => model.NodeTypeRbtn, "Cn", new { @class = "rbtnnodetype" })
                        </span>

                    </div>
                </div>
                <br />
                @Html.ValidationMessageFor(m => m.NodeTypeRbtn, "", new { @class = "alert-error" })
            </div>

            <div class="clearfix">
            </div>
            <div class="col-md-12">
                <div class="petenddiv hidden">
                    @Html.Label("Select Parent")
                    @Html.DropDownList("ParentName", new SelectList(ViewBag.plist, "MDA_ID", "MDA_NAME"), "--select--", new { @class = "form-control" })

                    @Html.ValidationMessageFor(m => m.ParentName, "", new { @class = "alert-error" })
                </div>
            </div>

            <div class="clearfix">
            </div>

            <div class="col-md-12">
                <div>
                    @Html.Label("MDA Name")
                    @Html.TextBoxFor(model => model.NodeName, new { @class = "form-control" })

                    @Html.ValidationMessageFor(model => model.NodeName, "", new { @class = "alert-error" })
                </div>

            </div>

<div class="col-md-12">
    <div>
        @Html.Label("Description")
        @Html.TextBoxFor(model => model.NodeDescription, new { @class = "form-control" })

        @Html.ValidationMessageFor(model => model.NodeDescription, "", new { @class = "alert-error" })
    </div>

</div>
<div class="col-md-12">
    <div>
        @Html.Label("Organization Type")

        @Html.DropDownListFor(model => model.NodeOrganizationType, new List<SelectListItem>
                                    {
                                        new SelectListItem{Text = "Agency", Value = "Agency"},
                                        new SelectListItem{Text = "Commission", Value = "Commission"},
                                        new SelectListItem{Text = "Department", Value = "Department"},
                                        new SelectListItem{Text = "Ministry", Value = "Ministry"}
                                    }, "Select Error Type", new { @style = "border-radius:3px;", @type = "text", @class = "form-control", @placeholder = "Enter Organization Type", @autocomplete = "on" })

        @Html.ValidationMessageFor(model => model.NodeDescription, "", new { @class = "alert-error" })
    </div>

</div>

            <div class="clearfix">
            </div>
            <br />
            <br />
            <div class="col-md-12">
                <div>
                    <div class="pull-left">
                        <input type="submit" id="savenode" value="S A V E" class="btn btn-primary" />
                    </div>

                    <div class="pull-right">
                        <input type="button" id="closePopOver" value="C L O S E" class="btn btn-primary" />
                    </div>
                </div>
            </div>


            <div class="clearfix">
            </div>


        }

    </div>
</div>

View

<div class="col-md-12" style="margin:100px auto;">
<div class="modal fade in" id="modalAddNode" role="dialog" aria-hidden="true">
    @Html.Partial("_AddNode")
</div>

<div class="col-md-12">
    <div class="panel panel-primary">
        <div class="panel-heading">Ministries, Departments and Agencies -: [ Add MDA and its Members ]</div>

        <div class="panel-body">
            <div id="tree"></div>

            <div class="clearfix">
            </div>

            <br />
            <div>
                <button id="btnDeleteNode" data-toggle="modal" class='btn btn-danger'> Delete Node <span class="glyphicon glyphicon-trash"></span> </button>
                <button id="btnpopoverAddNode" data-toggle="modal" class='btn btn-warning'> Add Node <span class="glyphicon glyphicon-plus"></span>  </button>
            </div>
        </div>
    </div>
</div>

Scipts

@section Scripts {
    @System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
    <script src="@Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
    <script src="~/Scripts/Gijgo/gijgo.js"></script>
    <link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        //'Hierarchy/GetHierarchy'
        $(document).ready(function () {
            var Usertree = "";
            var tree = "";
            $.ajax({
                type: 'get',
                dataType: 'json',
                cache: false,
                url: '/Mda/GetHierarchy',
                success: function (records, textStatus, jqXHR) {
                    tree = $('#tree').tree({
                        primaryKey: 'MDA_ID',
                        dataSource: records,
                        dragAndDrop: true,
                        checkboxes: true,
                        iconsLibrary: 'glyphicons',
                        //uiLibrary: 'bootstrap'
                    });
                    Usertree = $('#Usertree').tree({
                        primaryKey: 'MDA_ID',
                        dataSource: records,
                        dragAndDrop: false,
                        checkboxes: true,
                        iconsLibrary: 'glyphicons',
                        //uiLibrary: 'bootstrap'
                    });

                    tree.on('nodeDrop', function (e, MDA_ID, PARENT_MDA_ID) {
                        currentNode = MDA_ID ? tree.getDataById(MDA_ID) : {};
                        console.log("current Node = " + currentNode);
                        parentNode = PerentId ? tree.getDataById(PARENT_MDA_ID) : {};
                        console.log("parent Node = " + parentNode);

                        if (currentNode.PARENT_MDA_ID === null && parentNode.PARENT_MDA_ID === null) {
                            alert("Parent node is not droppable..!!");
                            return false;
                        }
                        // console.log(parent.HierarchyLevel);
                        var params = { MDA_ID: MDA_ID, PARENT_MDA_ID: PARENT_MDA_ID };
                        $.ajax({
                            type: "POST",
                            url: "/Mda/ChangeNodePosition",
                            data: params,
                            dataType: "json",
                            success: function (data) {
                                $.ajax({
                                    type: "Get",
                                    url: "/Mda/GetHierarchy",
                                    dataType: "json",
                                    success: function (records) {
                                        Usertree.destroy();
                                        Usertree = $('#Usertree').tree({
                                            primaryKey: 'MDA_ID',
                                            dataSource: records,
                                            dragAndDrop: false,
                                            checkboxes: true,
                                            iconsLibrary: 'glyphicons',
                                            //uiLibrary: 'bootstrap'
                                        });
                                    }
                                });

                            }
                        });

                    });

                    $('#btnGetValue').click(function (e) {
                        var result = Usertree.getCheckedNodes();
                        if (result == "") { alert("Please Select Node..!!") }
                        else {
                            alert("Selected Node id is= " + result.join());
                        }
                    });
                       //delete node
                    $('#btnDeleteNode').click(function (e) {
                        e.preventDefault();
                        var result = tree.getCheckedNodes();
                        if (result != "") {
                            $.ajax({
                                type: "POST",
                                url: "/Mda/DeleteNode",
                                data: { values: result.toString() },
                                dataType: "json",
                                success: function (data) {
                                    alert("Deleted successfully ");
                                    window.location.reload();
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    alert('Error - ' + errorThrown);
                                },
                            });
                        }
                        else {
                            alert("Please select Node to delete..!!");
                        }


                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('Error - ' + errorThrown);
                }
            });

            // show model popup to add new node in Tree
            $('#btnpopoverAddNode').click(function (e) {
                e.preventDefault();
                $("#modalAddNode").modal("show");
            });

            //Save data from PopUp
            $(document).on("click", "#savenode", function (event) {
                event.preventDefault();
                $.validator.unobtrusive.parse($('#formaddNode'));
                $('#formaddNode').validate();
                if ($('#formaddNode').valid()) {
                    var formdata = $('#formaddNode').serialize();
                    // alert(formdata);
                    $.ajax({
                        type: "POST",
                        url: "/Mda/AddNewNode",
                        dataType: "json",
                        data: formdata,
                        success: function (response) {
                            // $("#modalAddNode").modal("hide");
                            window.location.reload();
                        },
                        error: function (response) {
                            alert('Exception found');
                            //  $("#modalAddNode").modal("hide");
                            window.location.reload();
                        },
                        complete: function () {
                            //  $('.ajax-loader').css("visibility", "hidden");
                        }
                    });
                }

            });

            //Close PopUp
            $(document).on("click", "#closePopup", function (e) {
                e.preventDefault();
                $("#modalAddNode").modal("hide");
            });

            $('.rbtnnodetype').click(function (e) {
                if ($(this).val() == "Pn") {
                    $('.petenddiv').attr("class", "petenddiv hidden");

                    $("#ParentName").val("");
                }
                else {
                    $('.petenddiv').attr("class", "petenddiv");
                }
            });

        });

    </script>

}

Treeview

As shown above, what I have created can only do one level node. I want want to create multi-level.Whereby, a child will be a parent to other children.

Please how do I achieve this.

1 Answer 1

1

You can see some ASP.NET examples about this at https://github.com/atatanasov/gijgo-asp-net-examples/tree/master/Gijgo.Asp.NET.Examples Please use our examples in order to achieve that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.