August, 2009 Results

Using jQuery with ASP.NET Controls

Thursday, August 6th, 2009

jQuery, a lightweight (only 19kb in size) JavaScript library has become my new best friend. It’s like mushrooms to Mario. Obviously I’m not alone since Microsoft is now distributing jQuery with Visual Studio (including jQuery intellisense). If you are using the new MVC framework from Microsoft then you will no doubt become familiar with the intricate workings of jQuery.

jQuery is not all that difficult to learn. The biggest thing you have to understand is all the different “selectors” that are available to you. Using selectors developers can query, in a CSS like way, for HTML elements, and then apply “commands” to them.

For example, the below JavaScript uses jQuery to find a <div> element within a page that has a CSS id of “rightSide”, and shows it and “leftSide” and hides it.

javascript

  1. $('div#rightSide').show();
  2. $('div#leftSide').hide();

As another example, the JavaScript below uses jQuery to find a specific <table> on the page with an id of “datagrid1”, then retrieves every other <tr> row within the datagrid, and sets those <tr> elements to have a CSS class of “even” – which could be used to alternate the background color of each row:

javascript

  1. $('#datagrid1 tr:nth-child(even)').addClass('even');

This next example gets all links <a> in a specific <div> and attaches an onclick event to them:

javascript

  1. $('#navBtns a').bind('click', function(event){
  2.      event.preventDefault(); //stop the link from going to href
  3.      //do something
  4. });

Being able to traverse the DOM and locate HTML elements to attach events, behaviors, animations and CSS is priceless. But what about ASP.NET controls like the RadioButtonList, GridView, ListView, Repeater, and many others that we as developers like to bind to? How do we traverse them when they all get their ids auto-generated? That’s what we will look at now! And with jQuery it’s not that hard!

(more…)

mulberry sale spyder womens jacket cheap new balance 574 mulberry outlet cheap new balance 574 arcteryx outlet mulberry sale spyder womens jacket mulberry sale spyder womens jacket mulberry outlet mulberry outlet new balance 574

Popular Articles

Top 10 Commentators


Subscribe to this feed! Subscribe by Email!

Random Bits Podcast

You need to download the Flash player from Adobe

Blogs Worth Reading