However, TreeNode is a special case in that. There is no straightforward way to hookup client events to it. This is simply because they are rendered as Anchor <a> elements and its href and onClick attributes are itself consumed by ASP.NET framework.
However, with a little trick, the TreeNode element can be easily hooked up to client events.
The key to this solution is TreeNode’s PreRenderText and PostRenderText methods. The framework describes it as :
RenderPostText: Allows control developers to add additional rendering to the node.
RenderPreText: Allows control developers to add additional rendering to the node.
Using these methods, we can inject a simple <div> tag and enclose our Nodes(<a>) in those. For example:
The code above will call the CheckUnsavedStatus client function passing it the reference of <div> element. Using this <div> element, we can alter our Node(<a> element) at the client side.
For example, We might want to call the server side event SelectedNodeChanged, only if user has saved its changes. The client script for this kind of scenario would be:
The function above changes the target link of node to # which suppresses the server side call and subsequently the postback. Here, hiddenSaveDataCheck is a HiddenField which tracks the save/unsaved status.
To preserve the custom script generation on postback, the CreateNode method of TreeView control must be overrideen to return our CustomNode rather than default TreeNode implementation. This is easy:
Another important thing to be kept in mind is SelectAction property of TreeNode. This property determines, what happens when you click a TreeNode. This is an enumeration described as :
TreeNodeSelectAction.None: Raises no events when a node is selected.
TreeNodeSelectAction.Select: Raises the SelectedNodeChanged event when a node is selected.
This solution will work for all the cases irrespective of the setting, however it hardly makes it any sense to set it as TreeNodeSelectAction.None, since in this case, node is not rendered as hyperlink. For only client event, it should preferably be set to TreeNodeSelectAction.Select. Since this also causes a server side event SelectedNodeChanged, we can suppress the postback in our client function as discussed above.