Tuesday, July 17, 2012

Simple TreeView in MVC3 using Entity Framework Code First




This week I had to create a tree structure in my work, so I made a little research about it and I found this useful post that helped me to finish:
http://weblogs.asp.net/mikebosch/archive/2008/11/25/hierarchical-treeview-with-asp-net-mvc-jquery.aspx

The example above was written in MVC 2, so I made an upgrade to MVC3 using EF Code First with Razor, so I could dynamically add items by indicating the parent's ID.

Model

The model is really simple (based on the link posted above), I'm just indicating that the tree model can have a collection of itself (Group) and the relation is between the Id and the Parent_Id.

public class Tree
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public int? Parent_Id { get; set; }
        [ForeignKey("Parent_Id")]
        public virtual ICollection<Tree> Group { get; set; }
    }

Controller

I created a controller named 'Show', which will call all the items where its parent ID equals null; meaning that these items are roots of the tree structure.

public ViewResult Show()
        {
            var roots = db.Tree.Where(r => r.Parent_Id == null);
            return View(roots);
        }

View

I used 2 views, one for display the roots of the structure (Show view), and the other for displaying all the child elements (TreeItem view).

Show View:
@model IEnumerable<TreeView.Models.Tree>
<ul>
    @Html.Partial("~/Views/Tree/TreeItem.cshtml")
</ul>
TreeItem View:
@model IEnumerable<TreeView.Models.Tree>
@{
    Layout = null;
}

@foreach(var item in Model){
    <li>
        @item.Name
        @if (item.Group.Count > 0)
        {
            <ul>
                @{Html.RenderPartial("~/Views/Tree/TreeItem.cshtml", item.Group);}
            </ul>
        }
    </li>
}

No comments:

Post a Comment