using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; namespace Bowin.Web.Controls.Mvc { public static class CheckListTreeExtensions { public static MvcHtmlString CheckListTree(this HtmlHelper htmlHelper, ListTreeOptions listTreeOptions) { var topItems = listTreeOptions.ItemList.Where(x => x.ParentValue == null).ToList(); if (listTreeOptions == null) { listTreeOptions = new ListTreeOptions(); } if((listTreeOptions.ItemName ?? "") == "") { listTreeOptions.ItemName = "checkBoxTreeList" + Guid.NewGuid().ToString(); } if ((listTreeOptions.LeafWidth ?? 0) < 1) { listTreeOptions.LeafWidth = 1; } StringBuilder html = new StringBuilder(); for (int i = 0; i < topItems.Count; i ++ ) { string myID = listTreeOptions.ItemName +Guid.NewGuid()+ i; int level = 0; html.AppendFormat("
{1}
", topItems[i].Value, topItems[i].Text, listTreeOptions.ItemName, ((listTreeOptions.SelectedValues.Contains(topItems[i].Value)) ? " checked" : ""), myID); AddSubItems(html, listTreeOptions, myID, topItems[i], level); } return MvcHtmlString.Create(html.ToString()); } private static void AddSubItems(StringBuilder html, ListTreeOptions listTreeOptions, string parentID, ListTreeItem item, int level) { var curItems = listTreeOptions.ItemList.Where(x => (x.ParentValue != null) ? x.ParentValue.Equals(item.Value) : false); var leafItems = curItems.Where(x => !listTreeOptions.ItemList.Exists(y => (y.ParentValue != null) ? y.ParentValue.Equals(x.Value) : false)).ToList(); var branchItems = curItems.Where(x => !leafItems.Contains(x)).ToList(); var nowLevel = level + 1; int rowCount = Convert.ToInt32(Math.Ceiling(((double)leafItems.Count()) / listTreeOptions.LeafWidth.Value)); for (int i = 0; i < rowCount; i ++) { html.Append("
"); for (int k = 0; k < nowLevel; k++) { html.Append("  "); } for (int j = 0; j < listTreeOptions.LeafWidth; j++) { var curIndex = i * listTreeOptions.LeafWidth.Value + j; if (leafItems.Count > curIndex) { string myID = parentID + "l" + curIndex; html.AppendFormat("{1}", leafItems[curIndex].Value, leafItems[curIndex].Text, listTreeOptions.ItemName, ((listTreeOptions.SelectedValues.Contains(leafItems[curIndex].Value)) ? " checked" : ""), myID); } html.Append(" "); } html.Append("
"); } for (int i = 0; i < branchItems.Count; i ++ ) { string myID = parentID + i; html.Append("
"); for (int j = 0; j < nowLevel; j++) { html.Append("  "); } html.AppendFormat("{1}", branchItems[i].Value, branchItems[i].Text, listTreeOptions.ItemName, ((listTreeOptions.SelectedValues.Contains(branchItems[i].Value)) ? " checked" : ""), myID); html.Append("
"); AddSubItems(html, listTreeOptions, myID, branchItems[i], nowLevel); } } } }