title: How to create Multi-Level Treeview in ASP.NET MVC
body: <p>I have implemented a code to create Tree View and also save it into database.</p>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>        public ActionResult IndexMda()
      {
          using (BackendEntities context = new BackendEntities())
          {
              var plist = context.MDA.Where(p =&gt; p.PARENT_MDA_ID == null).Select(a =&gt; new
              {
                  a.MDA_ID,
                  a.MDA_NAME,
                  a.MDA_DESCRIPTION,
                  a.ORGANIZATION_TYPE
              }).ToList();
              ViewBag.plist = plist;
          }
          GetHierarchy();
          return View();
      }
      public JsonResult GetHierarchy()
      {
          List&lt;MDA2&gt; hdList;
          List&lt;MdaViewModel&gt; records;
          using (BackendEntities context = new BackendEntities())
          {
              hdList = context.MDA.ToList();
  
              records = hdList.Where(l =&gt; l.PARENT_MDA_ID == null)
                  .Select(l =&gt; 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&lt;MdaViewModel&gt; GetChildren(List&lt;MDA2&gt; hdList, long PARENT_MDA_ID)
      {
          return hdList.Where(l =&gt; l.PARENT_MDA_ID == PARENT_MDA_ID)
              .Select(l =&gt; 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 =&gt; 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);
      }
  </code></pre>
  
  <p>The partial view is where the Tree View is created
  <strong>Partial View</strong></p>
  
  <pre><code>@model BPP.CCSP.Admin.Web.ViewModels.AddNode
  
  &lt;div class="modal-dialog"&gt;
  &lt;div class="modal-content"&gt;
      &lt;div class="modal-header"&gt;
          &lt;button type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-label="Close"&gt;
              &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;
          &lt;/button&gt;
          &lt;h4 class="modal-title"&gt;Add Node&lt;/h4&gt;
      &lt;/div&gt;
      &lt;div class="modal-body"&gt;
          @using (Html.BeginForm("AddNewNode", "Mda", FormMethod.Post, new { @id = "formaddNode", @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
          {
              @Html.AntiForgeryToken()
              @Html.ValidationSummary(true)
  
              &lt;div class="col-md-12"&gt;
  
                  &lt;div class="col-md-6 row"&gt;
                      &lt;div class="input-group"&gt;
                          &lt;input type="text" class="form-control" value="Perent Node" readonly="readonly"&gt;
                          &lt;span class="input-group-addon"&gt;
                              @Html.RadioButtonFor(model =&gt; model.NodeTypeRbtn, "Pn", new { @class = "btn btn-primary  rbtnnodetype" })
                          &lt;/span&gt;
  
                      &lt;/div&gt;
                  &lt;/div&gt;
                  &lt;div class="col-md-6"&gt;
                      &lt;div class="input-group "&gt;
                          &lt;input type="text" class="form-control" value="Child Node" readonly="readonly"&gt;
                          &lt;span class="input-group-addon"&gt;
                              @Html.RadioButtonFor(model =&gt; model.NodeTypeRbtn, "Cn", new { @class = "rbtnnodetype" })
                          &lt;/span&gt;
  
                      &lt;/div&gt;
                  &lt;/div&gt;
                  &lt;br /&gt;
                  @Html.ValidationMessageFor(m =&gt; m.NodeTypeRbtn, "", new { @class = "alert-error" })
              &lt;/div&gt;
  
              &lt;div class="clearfix"&gt;
              &lt;/div&gt;
              &lt;div class="col-md-12"&gt;
                  &lt;div class="petenddiv hidden"&gt;
                      @Html.Label("Select Parent")
                      @Html.DropDownList("ParentName", new SelectList(ViewBag.plist, "MDA_ID", "MDA_NAME"), "--select--", new { @class = "form-control" })
  
                      @Html.ValidationMessageFor(m =&gt; m.ParentName, "", new { @class = "alert-error" })
                  &lt;/div&gt;
              &lt;/div&gt;
  
              &lt;div class="clearfix"&gt;
              &lt;/div&gt;
  
              &lt;div class="col-md-12"&gt;
                  &lt;div&gt;
                      @Html.Label("MDA Name")
                      @Html.TextBoxFor(model =&gt; model.NodeName, new { @class = "form-control" })
  
                      @Html.ValidationMessageFor(model =&gt; model.NodeName, "", new { @class = "alert-error" })
                  &lt;/div&gt;
  
              &lt;/div&gt;
  
  &lt;div class="col-md-12"&gt;
      &lt;div&gt;
          @Html.Label("Description")
          @Html.TextBoxFor(model =&gt; model.NodeDescription, new { @class = "form-control" })
  
          @Html.ValidationMessageFor(model =&gt; model.NodeDescription, "", new { @class = "alert-error" })
      &lt;/div&gt;
  
  &lt;/div&gt;
  &lt;div class="col-md-12"&gt;
      &lt;div&gt;
          @Html.Label("Organization Type")
  
          @Html.DropDownListFor(model =&gt; model.NodeOrganizationType, new List&lt;SelectListItem&gt;
                                      {
                                          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 =&gt; model.NodeDescription, "", new { @class = "alert-error" })
      &lt;/div&gt;
  
  &lt;/div&gt;
  
              &lt;div class="clearfix"&gt;
              &lt;/div&gt;
              &lt;br /&gt;
              &lt;br /&gt;
              &lt;div class="col-md-12"&gt;
                  &lt;div&gt;
                      &lt;div class="pull-left"&gt;
                          &lt;input type="submit" id="savenode" value="S A V E" class="btn btn-primary" /&gt;
                      &lt;/div&gt;
  
                      &lt;div class="pull-right"&gt;
                          &lt;input type="button" id="closePopOver" value="C L O S E" class="btn btn-primary" /&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
  
  
              &lt;div class="clearfix"&gt;
              &lt;/div&gt;
  
  
          }
  
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>View</strong></p>
  
  <pre><code>&lt;div class="col-md-12" style="margin:100px auto;"&gt;
  &lt;div class="modal fade in" id="modalAddNode" role="dialog" aria-hidden="true"&gt;
      @Html.Partial("_AddNode")
  &lt;/div&gt;
  
  &lt;div class="col-md-12"&gt;
      &lt;div class="panel panel-primary"&gt;
          &lt;div class="panel-heading"&gt;Ministries, Departments and Agencies -: [ Add MDA and its Members ]&lt;/div&gt;
  
          &lt;div class="panel-body"&gt;
              &lt;div id="tree"&gt;&lt;/div&gt;
  
              &lt;div class="clearfix"&gt;
              &lt;/div&gt;
  
              &lt;br /&gt;
              &lt;div&gt;
                  &lt;button id="btnDeleteNode" data-toggle="modal" class='btn btn-danger'&gt; Delete Node &lt;span class="glyphicon glyphicon-trash"&gt;&lt;/span&gt; &lt;/button&gt;
                  &lt;button id="btnpopoverAddNode" data-toggle="modal" class='btn btn-warning'&gt; Add Node &lt;span class="glyphicon glyphicon-plus"&gt;&lt;/span&gt;  &lt;/button&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>Scipts</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>@section Scripts {
      @System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
      &lt;script src="@Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"&gt;&lt;/script&gt;
      &lt;script src="~/Scripts/Gijgo/gijgo.js"&gt;&lt;/script&gt;
      &lt;link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" /&gt;
      &lt;script type="text/javascript"&gt;
          //'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 &amp;&amp; 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");
                  }
              });
  
          });
  
      &lt;/script&gt;
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><a href="https://i.stack.imgur.com/Lo981.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lo981.png" alt="Treeview"></a></p>
  
  <p>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.</p>
  
  <p>Please how do I achieve this.</p>