Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added TreeViewInMVC/App_Data/database-20230407.sql
Binary file not shown.
68 changes: 68 additions & 0 deletions TreeViewInMVC/Binders/TreeModelBinder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TreeViewInMVC.Models;
using Newtonsoft.Json;

namespace TreeViewInMVC.Binders
{
public class TreeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;

var listTreeHidden = JsonConvert.DeserializeObject<List<TreeModel>>(request.Form.Get("treeHidden"));

if (listTreeHidden.Count > 0)
{
var selectedIds = JsonConvert.DeserializeObject<List<int>>(request.Form.Get("treeHiddenSelected"));

if (selectedIds.Count > 0)
{
for (int i = 0; i < listTreeHidden.Count; i++)
{
if (selectedIds.Contains(listTreeHidden[i].Id))
listTreeHidden[i].Selected = true;
}

}

if (listTreeHidden.Count > 1)
{
var listWithoutParentId = listTreeHidden.Where(x => x.ParentId == null).ToList();

var newlist = new List<TreeModel>();

for (int i = 0; i < listWithoutParentId.Count; i++)
{
newlist.Add(OrganizeChildrenItems(listWithoutParentId[i], ref listTreeHidden));
}

listTreeHidden = newlist;

}
}

return listTreeHidden;
}

TreeModel OrganizeChildrenItems(TreeModel item, ref List<TreeModel> list)
{
if (!list.Any(x => x.ParentId == item.Id))
return item;

if (item.Childs == null)
item.Childs = new List<TreeModel>();

foreach (TreeModel child in list.Where(x => x.ParentId == item.Id))
{
item.Childs.Add(OrganizeChildrenItems(child, ref list));
}

return item;
}
}
}
10 changes: 7 additions & 3 deletions TreeViewInMVC/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TreeViewInMVC.Models;

Expand Down Expand Up @@ -34,5 +32,11 @@ public ActionResult TreeView()
return View(db.TreeModel.Where(x => !x.ParentId.HasValue).ToList());
}

[HttpPost]
public ActionResult TreeView(List<TreeModel> model)
{
return View(model);
}

}
}
4 changes: 4 additions & 0 deletions TreeViewInMVC/Global.asax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using TreeViewInMVC.Binders;
using TreeViewInMVC.Models;

namespace TreeViewInMVC
{
Expand All @@ -16,6 +18,8 @@ protected void Application_Start()
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

ModelBinders.Binders.Add(typeof(List<TreeModel>), new TreeModelBinder());
}
}
}
6 changes: 6 additions & 0 deletions TreeViewInMVC/Models/IdentityModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ public ApplicationDbContext()
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ApplicationDbContext>(null);
base.OnModelCreating(modelBuilder);
}

public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
Expand Down
50 changes: 48 additions & 2 deletions TreeViewInMVC/Models/Tree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
Expand Down Expand Up @@ -152,6 +153,9 @@ public override string ToString()

var listItems = _items.ToList();

var div = new TagBuilder("div");
div.MergeAttribute("id", "jstree");

var ul = new TagBuilder("ul");
ul.MergeAttributes(_htmlAttributes);
var li = new TagBuilder("li")
Expand All @@ -173,12 +177,41 @@ public override string ToString()
}
ul.InnerHtml += li.ToString();

return ul.ToString();
div.InnerHtml += ul.ToString();

var outerDiv = new TagBuilder("div");
outerDiv.InnerHtml += div.ToString();

var hiddenTreeData = new TagBuilder("input");
hiddenTreeData.MergeAttribute("id", "treeHidden");
hiddenTreeData.MergeAttribute("name", "treeHidden");
hiddenTreeData.MergeAttribute("type", "hidden");
hiddenTreeData.MergeAttribute("value", "");

outerDiv.InnerHtml += hiddenTreeData.ToString();

var hiddenTreeIdsSelecteds = new TagBuilder("input");
hiddenTreeIdsSelecteds.MergeAttribute("id", "treeHiddenSelected");
hiddenTreeIdsSelecteds.MergeAttribute("name", "treeHiddenSelected");
hiddenTreeIdsSelecteds.MergeAttribute("type", "hidden");
hiddenTreeIdsSelecteds.MergeAttribute("value", "");

outerDiv.InnerHtml += hiddenTreeIdsSelecteds.ToString();

return outerDiv.ToString();
}

private void AppendChildren(TagBuilder parentTag, T parentItem, Func<T, IEnumerable<T>> childrenProperty)
{
var children = childrenProperty(parentItem).ToList();

var enumerableList = childrenProperty(parentItem);

if (enumerableList == null)
{
return;
}

var children = enumerableList.ToList();
if (!children.Any())
{
return;
Expand Down Expand Up @@ -215,12 +248,25 @@ private TagBuilder GetLi(T item)
{
if (prop.Name.ToLower() == "id")
li.MergeAttribute("id", prop.GetValue(item, null).ToString());

if (prop.Name.ToLower() == "title")
li.MergeAttribute("data-title", prop.GetValue(item, null).ToString());

if (prop.Name.ToLower() == "description")
li.MergeAttribute("data-description", prop.GetValue(item, null) == null ? "" : prop.GetValue(item, null).ToString());

if (prop.Name.ToLower() == "parentid")
li.MergeAttribute("data-parentId", prop.GetValue(item, null) == null ? "" : prop.GetValue(item, null).ToString());

//li.GenerateId(prop.GetValue(item, null).ToString());
//object propValue = prop.GetValue(myObject, null);
// Do something with propValue
if (prop.Name.ToLower() == "sortorder")
li.MergeAttribute("priority", prop.GetValue(item, null).ToString());
}

li.MergeAttribute("treeJsElement", "treeJsElement");

return li;
}
}
Expand Down
1 change: 1 addition & 0 deletions TreeViewInMVC/Models/TreeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class TreeModel
public string Title { get; set; }
public string Description { get; set; }
public int? ParentId { get; set; }
public bool Selected { get; set; }
[ForeignKey("ParentId")]
public virtual TreeModel Parent { get; set; }
public virtual ICollection<TreeModel> Childs { get; set; }
Expand Down
2 changes: 2 additions & 0 deletions TreeViewInMVC/TreeViewInMVC.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<UseGlobalApplicationHostFile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<Use64BitIISExpress />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand Down Expand Up @@ -167,6 +168,7 @@
<Compile Include="App_Start\IdentityConfig.cs" />
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="App_Start\Startup.Auth.cs" />
<Compile Include="Binders\TreeModelBinder.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\ManageController.cs" />
Expand Down
60 changes: 47 additions & 13 deletions TreeViewInMVC/Views/Home/TreeView.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@
<h2>TreeView</h2>
<link href="~/Content/jstree/dist/themes/default/style.min.css" rel="stylesheet" />
<div class="form-body">
<div id="jstree">
<form method="post">
@*<div id="jstree">*@
@(Html.TreeView(Model)
.EmptyContent("root")
.Children(m => m.Childs)
.HtmlAttributes(new { id = "tree" })
.ChildrenHtmlAttributes(new { @class = "subItem" })
.ItemText(m => m.Title)
.ItemTemplate(
@<text>
<a href="@item.Description" desc="@item.Description">@item.Title</a>
</text>)
.EmptyContent("root")
.Children(m => m.Childs)
.HtmlAttributes(new { id = "tree" })
.ChildrenHtmlAttributes(new { @class = "subItem" })
.ItemText(m => m.Description)
.ItemTemplate(
@<text>
<a href="@item.Description" desc="@item.Description">@item.Title</a>
</text>)
)
</div>
@*</div>*@
<input type="submit" value="Submit" />
</form>
</div>
@section scripts
{
Expand All @@ -43,8 +46,39 @@
"icon": "fa fa-file icon-state-warning icon-lg"
}
},
"plugins": ["dnd", "state", "types", "sort", "checkbox"]
"plugins": ["dnd", "state", "types", "sort", "checkbox"],

});

$('#jstree').on('changed.jstree', function (e, data) {
var i, j, r = [], m = [];
for (i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).id);
}

$('#treeHiddenSelected').val(JSON.stringify(r));
});

});
</script>

let list = $("li[treejselement='treeJsElement']").map(function () { return $(this).attr("id"); }).get();

var elem = {}, n = [];

if (list.length > 0) {

for (var i = 0; i < list.length; i++) {
elem = $("li#" + list[i] + "[treejselement='treeJsElement']");
n.push({
Id: list[i],
Title: elem.data("title"),
Description: elem.data("description"),
ParentId: elem.data("parentid")
});
}

$('#treeHidden').val(JSON.stringify(n));
}

</script>
}