Monday, May 14, 2012

jQueryUI and ASP.NET Master Pages

Here is cool trick to save some time when using jQueryUI and ASP.NET with master pages. The thing that always seems to trip someone up is finding a control from the master page and trying to hit it with a jQuery call. When ASP.NET adds a control to the DOM and you are using master pages, the ID is actually changed from what you assigned in the designer. It seems to be fairly random and shouldn't be counted on for consistency or convention, aside from all of the randomness preceding the ID from the designer. After piddling around for a while, I did find something that will work. Consider the following code (This code assumes you have all of your links and css hooked up.):
<script type="text/javascript">
 
$(function ()
{           
  $('[id$=txtCal]').datepicker({
     showOn: "button",
     buttonImage: "../images/calendar16.png",
     buttonImageOnly: true,
     buttonText: 'Choose'
   }); 
}
</script>
By using the jQuery "ends with" selector ($=) I am able to find any control with an ID. So, by using this master page, ANY control that has an ID ending with 'txtCal' will be formatted to be a drop down calendar using jQueryUI. By using this sort of approach and following consistent naming conventions, you would be able to do most of your UI changes from your master pages, allowing for consistent theme style control over their implementation. This also opens the door for driving more jQuery behavior from the the master page.