Run javascript function after asp.net TreeView TreeNodePopulate event

459 views Asked by At

I have a TreeView control with PopulateOnDemand option. After every firing of TreeNodePopulate event I need to call a javascript function. I've tried this

code behind:

protected void tvMyTree_PopulateNode(object sender, TreeNodeEventArgs e)
{
     TreeManager.PopulateNodes(e.Node.Value);              
    ClientScript.RegisterStartupScript(this.GetType(),"ScriptInitButtons", "InitButtons();", true);
}

js:

    <script type="text/javascript"> 
    function InitButtons() {
         $(".folder").button();
         $(".folder").click(function () {
              createFolderDialog.data('parentID', $(this).attr('id')).dialog('open');
         });
         $(".leaf").button();
   }
    </script>

But RegisterStartupScript is not working. The function call is not added into the page.

1

There are 1 answers

0
David J On BEST ANSWER

I found a solution here. However it didn't work with my version of ASP.NET without a tiny modification.

What this method does is modify the function that is called after the tree data is returned from the server. That function is called TreeView_ProcessNodeData and is found in WebForms.js. I had to inspect this file to see the names of its arguments. In this case the signature is TreeView_ProcessNodeData(n,t). It is important that you know the exact method signature.

Now we know the correct signature we create a function that runs on document ready. This finds gets TreeView_ProcessNodeData function as a string and extracts the method body. It then appends a line to the end of the method body that calls your InitButtons function. Finally it reassigns TreeView_ProcessNodeData to be a new function that takes the arguments 'n' and 't'.

From now on when the tree view called TreeView_ProcessNodeData it will call this new function which behaves just like the original except that it calls InitButtons at the end.

<script type="text/javascript">

    $(document).ready(updateTreeViewProcessNodeData);

    function updateTreeViewProcessNodeData() {
        // convert the TreeView_ProcessNodeData to a string
        var fnBody = TreeView_ProcessNodeData.toString();
        // remove everything before the first opening brace
        fnBody = fnBody.substring(fnBody.indexOf("{") + 1);
        // remove everything up to the last closing brace
        fnBody = fnBody.substring(0, fnBody.length - 1);
        // fnBody now contains the body of the method
        // add a new line at the end of the method to call InitButtons
        fnBody += "\nInitButtons();";
        // create a new function object from the text
        // 'n' and 't' are the correct names of the function arguments expected by the method body
        TreeView_ProcessNodeData = new Function("n", "t", fnBody);
    }

</script>