Published: 22 Jun 2007
By: Rakesh Bhatt
Download Sample Code

Context Menu on the nodes of Microsoft ASP.NET TreeView control.


Tree structures are part of today's interactive web development. These structures allow us to show hierarchical information on our web pages.

To accomplish such structures nothing is easier than using the TreeView control shipped by Microsoft with ASP.NET 2.0. This tree control has the ability to consume hierarchical data sources like XML files and then display the information. The client side user can expand and collapse nodes. He’s also able to click on nodes to send requests to the server.

Today's need of user interaction is much higher than that provided by the built-in TreeView control. This control would have more flexibility if the programmers were able to capture several other client side events, thus providing the users with more advanced features on the tree structure.

In this article I am going to show:

  • How to capture a right click event on a node of the tree.
  • How to display a custom context menu on right click.

We know that all the server controls are finally rendered as HTML/DHTML with a combination of JavaScript on the browser. If we can combine JavaScript with the HTML rendered by the TreeView control, we will be able to accomplish our task.

Tree View HTML rendering

A programmer can decide to create a tree view with the help of the tools available in Visual Studio. As an alternative, he can program the tree view in the source.

Figure 1 shows a tree view rendered by the ASP.NET TreeView control.

Figure 1: An ASP.NET TreeView control in the Visual Studio Designer.

Listing 1: ASP.NET code

When viewed in the browser, the whole tree is rendered with nested HTML TABLE and DIV elements, and some JavaScript. This is an example of tree node:

The node in the previous code snippet is rendered as follows:

The Trick

As we can see, the node’s text this is a test is rendered inside an anchor <a> tag. There are a number of text formatting tags - which support JavaScript - that can be nested inside the anchor tag. An example is the Bold tag <b>. The HTML would still be in correct format if we could embrace the node text inside tags that can be nested inside the <a> tag, so that the HTML rendering of the node looks like this:

The Bold tag also supports a number of browser events like click, double click, mouse over and so on. Any of these events can be used in the tag but we are interested in the oncontextmenu event. This event fires whenever the user right-clicks in the browser to bring up the context menu. Therefore, in our tag we can call any JavaScript function on this event. Our tag now looks like this:

This kind of HTML rendering can be easily achieved by writing the complete HTML as the node text. Thus, in the tree code, the node looks like:

Alternatively, you can write the HTML in the text property of the node:

Building the Menu

Once we are able to capture the contextmenu event, we want to produce our own menu instead of the default browser’s context menu. We can write any HTML combination within the DIV tags. This DIV division/section in the document can be moved around the document with the help of JavaScript.

We can also use the ASP.NET Panel control. When this control is rendered, it is rendered as a DIV division with same ID as the Panel control's ID. Therefore we can safely write our JavaScript function using the ID. Using the Panel makes it easier to build the menu and to control the menu object through ASP.NET 2.0 features.

Figure 2: The menu that we have used in this example

In the ASP.NET code we would like to add functionality to make the menu more interactive.

Listing 2: Code for the context menu

JavaScript Overview

Before we begin with writing the JavaScript code for our context menu, I would like to give an overview of some JavaScript objects and their properties. This will help us in bringing our context menu. The document object is the parent object of numerous other objects, such as images, forms and so on.

Table 1: Some of the properties of the document element

Property Description
document.getElementById("ID") A cross browser (IE5+/NS6+) DOM method for accessing any element on the page via its ID attribute.
Specifies the width and height, in pixels, of the window's content area respectively. Read/Write. Does not include the toolbar, scrollbars etc NS4 and NS6 equivalent are window.innerWidth, window.innerHeight
Returns an integer representing the pixels the current document has been scrolled from the upper left corner of the window, horizontally and vertically, respectively. NS4 and NS6+ IE4+ equivalents are window.pageXOffset, window.pageYOffset

The Event object (IE5+/NS6+) keeps tracks of various events that occur on the page - such as the user moving the mouse or clicking on the link - and allows the programmer to react to them.

Table 2: Some of the properties of the event object

Property Description
Returns the mouse coordinates at the time of the event relative to upper-left corner of the window.
event.cancelBubble Set to true to prevent the event from bubbling. NS equivalent stopPropagation()
Retrieves the width and height of the object relative to the layout or coordinate parent, as specified by the offsetParent property.

The Style object of the DOM allows you to dynamically change the values of your CSS properties, whether they are defined inline or via an external style sheet. The changes are instantly reflected in the page.

Event Bubbling

Internet Explorer 4.0x+ initially directs an event to its intended target. For example, if a button is clicked, the click event is directed to the button. The event invokes an event handler if one is defined for that object. If no event handler is defined to take care of the event - or if the event handler does not return false (to cancel the event) - the event proceeds to the parent object for handling. The event bubbles up the object hierarchy until it is handled, or until it reaches the top-most level, the document object.

We are able the capture the oncontextmenu event and with the help of our JavaScript code we will also be able to produce a custom menu. At the same time, though, we need to prevent the browser’s default menu from coming up.

The most important feature in Internet Explorer 4.0x+'s new event model is the event bubbling mechanism. In order to cancel bubbling for a specific event we must set the cancelBubble property of the event object to true, like so:

cancelBubble is a read-write property that takes a Boolean value. Its default value is false, specifying that the event should be bubbled up the hierarchy as usual. However, if explicitly set totrue, the event isn't bubbled, preventing the next event handler in the hierarchy to receive the event.

Another way to stop an event from bubbling is to entirely cancel the event by returning false in its event handler script or event processing function. However, unlike canceling bubbling for an event, if you cancel the event itself the default action associated with the event does not take place.

Listing 3: The JavaScript showmenuie5(event) function

Figure 3: The output


This article demonstrates how to capture the right click event on a tree node in order to display a context menu. The concept in this article can be applied to many other user interactive effects on the web pages, like mouse over effects on links to show little information dialog, draggable dialogs on the web page and so on.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Rakesh Bhatt

Sorry, no bio is available

View complete profile here.

Other articles in this category

Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.

You might also be interested in the following related blog posts

XAML TreeView with Context Menu, Drag and Drop features read more
A RouteHandler for IHttpHandlers read more
ASTreeView - A Powerful ASP.Net TreeView Control read more
Customizing the SharePoint ECB with Javascript, Part 3 read more
RadScheduler for Silverlight learning series, part 3: Add, Edit, and Delete Appointments read more
Customizing the SharePoint ECB with Javascript, Part 2 read more
Part 3: Accessing Security and Authentication in Silverlight using .NET RIA Services. read more
Customizing the SharePoint ECB with Javascript, Part 1 read more
A new treeview control - ASTreeView for you to use! :) read more
Using the ObjectScope events read more


Subject Author Date
placeholder TreeView Default Context Menu Ken Wilkinson 2/5/2008 9:11 AM

Please login to rate or to leave a comment.