分享

其实我想说我也有棵树:带线的无限级树(可以应用在任何地方,只要你想)

 贾朋亮博客 2011-08-03

昨天无意中看到"路过秋天"老大的一个带线的树,十分亲切因为在过去几天前我也弄了一棵,由于水平有限一时间就没有晒出来的意思,今天想来,这个想法是不对的!于是我决定接受大家的批评!我想强调的是我的Demo建立在asp.net mvc上,我想您没必要跟我一样,你可以采用任何项目类型!废话不多说了,贴上我的代码!

1.首先您得有这样结构的表

顺便在您建的项目的Models文件夹中建立一个Linq to sql 类,并且把如上图的表拉进去!在这里我叫这张表为"Category"!

2.建立对数据库的访问类 "CategoryRepository"

01 public class CategoryRepository {
02         TreeDemoDataContext dataContext = new TreeDemoDataContext();
03   
04         public IList<Category> GetAll() {
05             return dataContext.Category.ToList<Category>();
06         }
07   
08         public void Add(Category category) {
09             dataContext.Category.InsertOnSubmit(category);
10             Save();
11         }
12   
13         public Category Get(int id) {
14             return GetAll().SingleOrDefault(c => c.ID == id);
15         }
16   
17         public void Save() {
18             dataContext.SubmitChanges();
19         }
20     }

接下来才是重点角色,我自己封装了一个"TreeHelper"的类,方便日后在别的地方用!具体结构是这样的:

01 public class TreeHelper {
02        public TreeHelper() {
03            GetNode(0); //default pid=0
04        }
05  
06        #region Calculate Tree Node
07        private string[] icon = new string[] { "│", "├", "└" };
08        public IList<Category> arr = new List<Category>();
09  
10        public void GetNode(int? pid, string adds = "") {
11            int number = 1;
12  
13            IList<Category> list = new CategoryRepository().GetAll().Where(c=>c.PID==pid).ToList<Category>();
14            if (list != null && list.Count != 0) {
15                CalcNode(list, number, adds);
16            }
17        }
18  
19        // calculate tree node
20        private void CalcNode(IList<Category> list, int number, string adds) {
21            foreach (var category in list) {
22                string k = "", spacer;
23                JudgeShowStyle(list, out k, out spacer, number, adds);
24                category.Name = spacer + category.Name;
25                arr.Add(category);
26                GetNode(category.ID, adds + k + " ");// 
27                number++;
28            }
29        }
30  
31        //
32        // Judge show tree style
33        private void JudgeShowStyle(IList<Category> list, out string k, out string spacer, int number, string adds) {
34            string j = "";
35            k = "";
36            if (number == list.Count) {
37                j += icon[2];
38            } else {
39                j += icon[1];
40                k = adds != "" ? icon[0] : "";
41            }
42            spacer = adds != "" ? adds + j : "";
43        }
44        #endregion
45    }

我想我没必要讲解这些方法是干什么用的,因为注释已经写的很明白了!GetNode(0) 是默认显示的是根节点,也就是父亲节点为0的!

为了呆会在页面上操作我还写了一个"HomeModel"放在"Models"文件夹中,如下:

 

1 public class HomeModel {
2     public IList<Category> Categorys { get; set; }
3 }

3.定义HomeController

01 [HandleError]
02    public class HomeController : Controller
03    {
04        TreeHelper treeHelper = null;
05        HomeModel Model = new HomeModel();
06        CategoryRepository repository = new CategoryRepository();
07        Category category = null;
08        public ActionResult Index() {
09            treeHelper=new TreeHelper();
10            Model.Categorys = treeHelper.arr;
11            return View(Model);
12        }
13  
14        public ActionResult Add() {
15            return View();
16        }
17  
18        [AcceptVerbs(HttpVerbs.Post)]
19        public ActionResult Add(int id,FormCollection formValues) {
20            category = new Category();
21            UpdateModel(category);
22            category.PID = id;
23            repository.Add(category);
24            return RedirectToAction("Index");
25        }
26  
27        public ActionResult Create() {
28            return View();
29        }
30    }

关于视图您可以按照上面的Action依次添加:

Home/Index

01 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TreeDemo.Models.HomeModel>" %>
02   
03 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
04     Tree Demo
05 </asp:Content>
06   
07 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
08 <h2>应用在Table中</h2>
09     <table>
10         <tr>
11             <th>ID</th>
12             <th>Name</th>
13             <th>Description</th>
14             <th>Operation</th>
15         </tr>
16   
17     <% foreach (var item in Model.Categorys) { %>
18         <tr>
19            <td><%:Html.Encode(item.ID) %></td>
20            <td><%:Html.Encode(item.Name) %></td>
21            <td><%:Html.Encode(item.Description) %></td>
22             <td>
23                 <%: Html.ActionLink("Add child node", "Add", new { id=item.ID}) %>
24             </td>
25         </tr>
26       
27     <% } %>
28   
29     </table>
30     <h2>应用在DropDownList中</h2>
31     <select>
32     <%foreach (var category in Model.Categorys)
33       {%>
34         <option value="<%:Html.Encode(category.ID) %>"><%:Html.Encode(category.Name) %></option>
35         <%} %>
36     </select>
37     <p>
38         <%: Html.ActionLink("Create Root node", "Create")%>
39     </p>
40   
41 </asp:Content>

Home/Add

01 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
02   
03 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
04     Add child node
05 </asp:Content>
06   
07 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
08   
09     <h2>Add child node</h2>
10         <%using (Html.BeginForm()) {%>
11         <% Html.RenderPartial("Form"); %>
12         <p>
13             <input type="submit" value="Add" />
14         </p>
15     <%} %>
16 </asp:Content>

Home/Create

01 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TreeDemo.Models.HomeModel>" %>
02   
03 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
04     Create
05 </asp:Content>
06   
07 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
08   
09     <h2>Create</h2>
10     <%using (Html.BeginForm("Add", "Home", new { id = 0 }, FormMethod.Post))
11           {%>
12         <% Html.RenderPartial("Form"); %>
13         <p>
14             <input type="submit" value="Add" />
15         </p>
16     <%} %>
17 </asp:Content>

这里有一个RenderPartial视图Form.ascx:

01 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
02     <table>
03         <tr>
04             <td>
05             Name
06             </td>
07             <td>
08             <%:Html.TextBox("Name")%>
09             </td>
10         </tr
11         <tr>
12         <td>
13             Description
14             </td>
15             <td>
16             <%:Html.TextBox("Description")%>
17             </td>
18         </tr>
19     </table>

如果你干了这些事以后我想你的页面可以跑起来了,上几个图看看效果,俗话说有图有真相:

好了,比较简单,刚出道不久写作及技术水平有限!不管怎样,希望您能给点评价!
请尊重劳动http://www.cnblogs.com/chenkun

源代码下载

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多