Creating a simple Context Menu on a databound ASP.NET treeview

Recently, I was in need of a right-click context menu for the ASP.NET treeview control.  I know there are many third party & open source treeview controls that have this functionality built-in, but my situation demanded that I build my own.  After much Googling, I found that most of the posted code for creating your own is complicated at best.  So, having the MS AjaxControlToolkit already in heavy use on the project, I decided to utilize it.  Here's what I came up with:

I first created a menu in an asp:Panel & added a popupControlExtender from the MS AJAX Control Toolkit:

    
New Folder
Upload File

Delete Folder

Adjust Permissions

I then added the following attribute to the asp:TreeView tag:
oncontextmenu="ShowTreeviewContextMenu(this, event);
Finally, I created a javascript method to handle the treeview event & display the popup in the proper place:
function ShowTreeviewContextMenu(sender, menuEvent)
{
    var selectedNode = event.srcElement || event.target;//srcElement for Firefox, target for IE
    
    //Select the treeview node, then click it to highlight it.
    //This functionality may not be desirable for all applications.
    TreeView_SelectNode(<%= TreeView1.ClientID %>_Data, selectedNode, selectedNode.id.toString());
    selectedNode.click();

    //Cancel Standard Context Menu
    if (menuEvent.preventDefault) //For Firefox & other browsers that support preventDefault
    {
        menuEvent.preventDefault();
        menuEvent.stopPropagation();
    }
    else if (window.event)//For IE & others that support window.event
    {
        menuEvent.cancelBubble = true;
        menuEvent.returnValue = false;
    }
    
    //Ensure that the user clicked an actual node, not just somewhere in the treeview
    if (!selectedNode.id || selectedNode.id.length <= 0 || selectedNode.innerText !== selectedNode.innerHTML) return;
    
    //Display popup next to cursor
    $find("PopupControlExtenderTreeViewContextMenu").showPopup();
    var contextMenuPopup = document.getElementById("<%= PanelTreeViewContextMenu.ClientID %>");
    contextMenuPopup.style.position = 'absolute';
    contextMenuPopup.style.left = menuEvent.clientX + 'px';
    contextMenuPopup.style.top = menuEvent.clientY + 'px';
}
With this code in place, all I had to do is create javascript methods to handle the menu item clicks (on each of the div tags in the first code block above).

Comments

Post a Comment

Popular posts from this blog

Fixing Conan Lock Issues

Dynamic Object Oriented programming in ArchestrA

Initialize With Care