Saturday, December 10, 2011

Retrieving a Nested ASP.Net Object with Javascript & jQuery

Though I consider myself to be an accomplished C# / ASP.Net web developer, one of my weaknesses lies with client-side Javascript programming. I don't like the free-form, type unsafe nature of it and firmly believe that long term maintainability of Javascript code is a nightmare. The introduction of jQuery has improved things somewhat but there are still times when things can get very tricky. One prime example involves working with nested ASP.Net controls. Here's a quick example of such a situation:

What you're seeing in this image are a number of Telerik controls (which I highly recommend!) that provide a superb user experience for the application I'm building.
My task at hand was to add some custom client-side code for when an item in the listbox was double-clicked.










Here's a snippet of the layout code for the page:

  
    
      
        
          
The challenge was to obtain the ListBox from within the nested objects. Here's a sample Javascript function, that utilizes jQuery, to retrieve the RadListBox object:
 function rlbDoubleClicked() {
   var slidingZone = $find($('table[id$=_radSlidingZone]')[0].id);
   var slidingPane = slidingZone.getPanes()[0];

   // Standard Approach
   var listBox = $find($("#" + slidingPane.get_id() + " #<%= radListBoxStopes.ClientID %>")[0].id);

   // Alternate Approach (necessary if the function is to be placed in an external Javascript file)
   var listBox = $find($("#" + slidingPane.get_id() + " div[id$=_radListBoxStopes]")[0].id);
 }
Hopefully this example will help others with their own projects!

No comments:

Post a Comment