Telerik MVC : Adding a Context Menu to the TreeView

This website is no longer actively supported

Written by John DeVight on 03 Jun 2011 20:24
Last Updated by John DeVight on 15 Mar 2013 20:40

Download RAZOR Source Code
Download ASPX Source Code
* Note: the Telerik.Web.Mvc.dll, Telerik "Contents" and Telerik "Scripts" have all been removed to reduce the zip file size

Overview

I recently needed to implement a context menu in the Telerik MVC TreeView, but found that the TreeView does not have a context menu. I did some searching and found a post on the Telerik Forum about it in which a member of the Telerik team posted some sample code on how to add a context menu to the TreeView. I decided to take the code and extend the treeview by adding an "addContextMenu" function. The code has been incorporated into the Telerik Extensions For ASP.NET MVC : Extended Client API project on CodePlex in Change Set 6457.

In the article Telerik MVC : Creating an "ExtJS border-layout" with Splitters I demonstrated creating a nice desktop application look-and-feel for a web application. In this article I add to the code to demonstrate adding more than one context menu to the TreeView and displaying the appropriate context menu depending on the tree node that is selected.

Adding the TreeView

I created a partial view called _Navigation for the TreeView. I added an Ajax Select to get the TreeViewItems from the Home Controller and I added the OnLoad client event to add the context menus.

Here is the code for the _Navigation partial view:

@using Telerik.Web.Mvc.UI;
@{Html.Telerik().TreeView()
        .Name("NavigationTreeView")
        .DataBinding(dataBinding => dataBinding
            .Ajax().Select("NavigationTreeItems", "Home")
        )
        .ClientEvents(events => events.OnLoad("Layout.NavigationTreeView_OnLoad"))
        .Render();
}

I then added the _Navigation partial view to the Layout / Master page. Here is the code:

@Html.Partial("_Navigation")

Next I added the code to the Home Controller to return the list of TreeViewItems to be rendered in the TreeView. For the Project nodes, I set a value of "project|index". For the Code File nodes, I set a value of "codefile|index". This allowed me to differentiate between the different types of nodes.

Here is the code:

public JsonResult NavigationTreeItems()
{
    List<TreeViewItem> treeNodeList = new List<TreeViewItem>();
 
    TreeViewItem tviRoot = new TreeViewItem
    {
        Text = "My Solution",
        Value = "My Solution"
    };
    treeNodeList.Add(tviRoot);
 
    for (int pdx = 0; pdx < 5; pdx++)
    {
        TreeViewItem tviProject = new TreeViewItem
        {
            Text = string.Format("Project {0}", pdx),
            Value = string.Format("project|{0}", pdx)
        };
        tviRoot.Items.Add(tviProject);
 
        for (int cdx = 0; cdx < 10; cdx++)
        {
            TreeViewItem tviCodeFile = new TreeViewItem
            {
                Text = string.Format("Code File {0}", cdx),
                Value = string.Format("codefile|{0}", cdx)
            };
            tviProject.Items.Add(tviCodeFile);
        }
    }
 
    return Json(treeNodeList, JsonRequestBehavior.AllowGet);
}

Implementing the Context Menu

To implement the context menu, I added the telerik.extensions.js file to my project. I then registered the script in the Layout / Master page.

Last of all, I implemented the Layout.NavigationTreeView_OnLoad function in the Layout.js file where I add the context menus to the TreeView. The addContextMenu function takes a json object with two properties. They are:

  1. evaluateNode - a function that determines whether the context menu should be displayed for the node.
  2. menuItems - an array of json objects. Each json object has two properties for each menu item or a property called separator that indicates that a separator line should be displayed. The two properties for a menu item are:
    1. text - the text for the menu item
    2. onclick - the function to call when the menu item is clicked.

I added two context menus. The first context menu applies to the project node where I display a context menu with one menu item called Properties. When the user right clicks on the project node and clicks on Properties, the Layout.NavigationTreeView_OnProperties is executed. The second context meu applies to the code file node where I display a context menu with three menu items, Edit and Delete, a separator line and then Properties. When menu item is clicked the appropriate function is executed.

Here is the code:

Layout.NavigationTreeView_OnLoad = function(e) {
    $('#NavigationTreeView').data('tTreeView').addContextMenu({
        evaluateNode: function(treeview, node) {
            var nodeValue = treeview.getItemValue(node);
            var nodeType = nodeValue.split('|')[0].toString();
            return nodeType == 'project';
        },
        menuItems: [{
                text: 'Properties',
                onclick: Layout.NavigationTreeView_OnProperties
            }]
    });
 
    $('#NavigationTreeView').data('tTreeView').addContextMenu({
        evaluateNode: function(treeview, node) {
            var nodeValue = treeview.getItemValue(node);
            var nodeType = nodeValue.split('|')[0].toString();
            return nodeType == 'codefile';
        },
        menuItems: [{
                text: 'Edit',
                onclick: Layout.NavigationTreeView_OnEdit
            }, {
                text: 'Delete',
                onclick: Layout.NavigationTreeView_OnDelete
            }, {
                separator: true
            }, {
                text: 'Properties',
                onclick: Layout.NavigationTreeView_OnProperties
            }]
    });
}

The function that is executed when a menu item is clicked has a parameter that is a json object. The json object has three properties:

  1. item - this is the HTML <li> element for the menu item that was clicked.
  2. treeview - the TreeView associated with the context menu.
  3. node - the node where the user right clicked to display the context menu.

Here is the code for the three functions that I created to handle Edit, Delete and Properties:

Layout.NavigationTreeView_OnProperties = function(e) {
    alert('You Clicked ' + e.item.text() + ' for ' + e.treeview.getItemText(e.node) + ' with a value of ' + e.treeview.getItemValue(e.node));
}
 
Layout.NavigationTreeView_OnEdit = function(e) {
    alert('You Clicked ' + e.item.text() + ' for ' + e.treeview.getItemText(e.node) + ' with a value of ' + e.treeview.getItemValue(e.node));
}
 
Layout.NavigationTreeView_OnDelete = function(e) {
    alert('You Clicked ' + e.item.text() + ' for ' + e.treeview.getItemText(e.node) + ' with a value of ' + e.treeview.getItemValue(e.node));
}

References

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License