DCSIMG
You are reading a MIX Online Opinion. In which we speak our minds. DaveWard Meet Dave Arrow

Read More by Dave:

Opinion

22Comment Retweet

What ASP.NET Developers Should Know About jQuery

Apr 28, 2009 By Dave Ward

It’s hard to believe that JavaScript is already well over a decade old.  Often relegated to marginal tasks in its early years, JavaScript has grown to become a pillar of modern web development.  With the current popularity of DHTML and AJAX, it can be difficult to find a site that doesn’t use JavaScript anymore.  One of the driving forces behind JavaScript’s newfound popularity is a proliferation of JavaScript frameworks, such as jQuery.

Why?

Though JavaScript itself is a great programming language, the document object model (DOM) can be a web developer’s worst nightmare.  The DOM is a method through which browsers expose an interface allowing JavaScript code to manipulate elements, handle events, and perform other tasks related to a document within the browser.  While almost every browser implements an ECMA standard version of JavaScript, their DOM implementations are inconsistent and quirky at best.  In fact, if you’ve had bad experiences with client-side programming in the past, it’s likely that the DOM was the true source of your frustrations, not JavaScript itself.  This is exactly the pain point which jQuery addresses.

jQuery abstracts the DOM away, allowing you to focus on behavior instead of implementation.  It provides a simplified, reliable interface to the DOM that works consistently across all major browsers.  Instead of wasting time and effort supporting the idiosyncrasies of these browsers, you can write jQuery code that works the same across them all.

Why jQuery?  What’s in it for me?


  • CSS3 selectors – In jQuery, nearly everything begins with a selector that defines a set of one or more DOM elements.  By implementing a CSS3 compliant selector engine, jQuery provides tremendous flexibility in this area.  Selectors may contain any combination of ID, CSS class, and/or an expanded set of pseudo selectors (e.g. :first, :selected, :input).
  • DOM manipulation – One of the most common client-side tasks is making changes or additions to a rendered HTML document.  Whether updating a snippet of text or adding entire HTML structures, jQuery provides a robust set of utility functions that are up to the challenge.  Combined with the versatile selector engine, complex manipulations are possible with only a few lines of jQuery code.
  • Animation – The core jQuery library contains a few commonly used animations, such as fades and slides, and it also provides for specifying custom animations.  Beyond that, jQuery UI offers animated transitions between CSS classes and a wide variety of easings.
  • AJAX communication – No JavaScript framework would be complete without a way to make asynchronous requests, and jQuery is no exception.  jQuery provides AJAX communication through several methods which allow you to choose an appropriate balance between control and simplicity.
  • Plugins – jQuery’s straightforward extensibility model has led to a thriving plugin ecosystem.  As of this writing, there are almost 2,500 third-party plugins in the repository.  Everything from simple utility functions to entire client-side templating solutions are available as jQuery plugins.  If you can imagine a feature, it’s likely that a plugin already exists to assist you in implementing it.
  • Cross-browser compatibility – As previously mentioned, one of jQuery’s key strengths is that all of its features work consistently across every major browser.  Any jQuery code that you write will produce the same results in Internet Explorer 6.0+, Firefox 2.0+, Safari 3.0+, Opera 9+, and Chrome.
  • Officially supported by Microsoft – For many Microsoft developers, this official blessing is the clincher.  Not only will Microsoft begin including jQuery with Visual Studio, but it is part of the default ASP.NET MVC project template.  What’s more, Microsoft Product Support Services has already begun offering support for jQuery.

Coming from ASP.NET, what should I know?


If you’re coming from an ASP.NET development background, some of jQuery’s idioms may seem foreign at first.  As with any framework, it’s important to learn the conventions and use them to your advantage.  Going against the grain only wastes your time and effort.
In that spirit, these are a few specific tips that I hope will help you flatten the learning curve a bit.

  • Use selectors.  Think in sets.
    In the ASP.NET world, it’s rare to select sets of controls through queries. Instead, we’re accustomed to referencing a single control by its unique ID.  Of course this is possible in jQuery too, but its selector engine is far more sophisticated.

    Using selectors to identify a set of one or more elements is cleaner and more expressive than the iterative machinations you may be used to in ASP.NET server-side code.  Before parsing out an ID or iterating over a group of elements in search of certain ones, be sure that the task isn’t more easily accomplished through a jQuery selector.
  • Use CSS classes for more than just styling.
    Another technique that is counterintuitive at first is the use of CSS classes as flags.  Coupled with jQuery’s selector engine, “flag” classes are surprisingly powerful.

    A good object lesson comes from one of my recent contracts, where I was hired to add client-side interactivity to an online card game.  One of the requirements was that the card images should have OnClick handlers applied at particular times, but only to those cards which were face down.

    The .NET developer in me immediately considered maintaining the state of all the cards in some sort of client-side collection.  Then, I could have iterated over that array to set up the appropriate OnClick handlers when necessary.  That would have worked, but it would have been messy, prone to breakage, and generally difficult to maintain.

    Instead, I realized that CSS classes as flags would allow me to implement a more elegant solution.  Within the code that “flipped” the cards face up, I used addClass to add a “flipped” class to the card images.  Then, a simple $(“.card:not(.flipped)”) selected the set of cards which were face down.  Using jQuery’s click(fn) on that set of elements allowed me to implement the entire feature in just a few lines of code.  Perhaps more importantly, that code was far easier to read and understand than the alternative would have been.
  • Understand unobtrusive JavaScript.
    In the ASP.NET world, we use a lot of what’s sometimes termed obtrusive JavaScript.  This means that client-side event handlers are defined as attributes on elements.  For example, several ASP.NET WebControls render an OnClick=”javascript:__doPostBack()”attribute as part of their markup.  This is considered obtrusive JavaScript.

    When ASP.NET was initially being developed, this inline JavaScript was the norm.  However, as browsers began providing more sophisticated faculties for imperatively adding event handlers, this declarative technique quickly lost favor with client-side developers. As a consequence, the preferred approach has shifted toward what’s called unobtrusive JavaScript.

    Unobtrusive JavaScript is now considered a best practice when wiring up client-side event handlers.  This is primarily because it facilitates separation of concerns between behavioral JavaScript and structural HTML markup.  Unobtrusive JavaScript also helps you to write cleaner, more semantic markup, which improves accessibility and often has SEO benefits.
  • Use the console to learn interactively.
    Coming from the save-compile-reload paradigm of statically typed server-side development, it’s natural to approach client-side development in a similar fashion.  While you certainly can write client-side code that way, it’s akin to working blindfolded when you consider the alternatives.

    Since JavaScript is usually interpreted by a browser, the browser is one of the best debugging environments available.  In particular, a JavaScript “console” is terrific for interactively interrogating the DOM, testing jQuery selectors against actual markup, and refining JavaScript code in real-time.

    My preferred browser-based tool is the Firebug addon to Firefox.  I cannot praise this Firebug highly enough.  It has revolutionized how I approach client-side development, both of JavaScript and of CSS.  If you prefer Internet Explorer, IE8’s updated developer tools are also very capable in this department.
    Whatever your browser of choice, I urge you to give these utilities a try when debugging client-side functionality.  Once you become proficient with one of these tools, you’ll be amazed that you ever developed client-side code without it.
  • Get the VSDOC.
    Even though browser-based tools are great for debugging, an ASP.NET developer’s primary editor is still going to be Visual Studio.  When writing jQuery code in Visual Studio, having proper Intellisense can make a tremendous difference in productivity.  The discoverability that Intellisense provides is especially beneficial when you’re unfamiliar with jQuery’s API.

    As part of the official support for jQuery, Microsoft provides a documentation file to provide jQuery Intellisense inside Visual Studio 2008.  This is provided through what’s called a vsdoc file, and is available on the jQuery download page (via the “Documentation: Visual Studio” links).
    Jeff King has assembled an excellent FAQ to help you get Visual Studio 2008’s JavaScript Intellisense working:  http://blogs.msdn.com/webdevtools/archive/2008/11/18/jscript-intellisense-faq.aspx

Conclusion


By now, it’s probably no secret that I’m a proponent of jQuery and of Microsoft’s decision to officially support it.  Hopefully, some of the benefits outlined in this article have made it clear why.  After you’ve spent some hands-on time with the framework, I believe that you’ll begin to share my enthusiasm for it.

A common story I hear from ASP.NET developers is that they gave client-side development a fair chance several years ago, found writing cross-browser DOM code to be incredibly tedious, and have avoided it ever since.  If you’ve had that sort of bad experience with client-side programming in the past, there’s never been a better time to give it another try.  Between improved tooling and JavaScript frameworks such as jQuery, most of the old frustrations have been completely eliminated.

Case in point, the Glimmer application that the MIX team has just released is a great companion to your exploration of jQuery.  As far as I know, a task-oriented jQuery GUI is something that has not previously existed.  Kudos to the MIX team for bringing us this innovative new tool.

          Follow the Conversation

          22 Comments so far. You should leave one, too.

          Tim Misra (gravatar) Tim Misra said on April 29, 2009

          Wow – you hit it on the head.
          “If you’ve had that sort of bad experience with client-side programming in the past, there’s never been a better time to give it another try”

          Thanks – keep up the good work.

          Tim Misra
          MCP, MCAD.Net, MCSD.Net

          Muhammad Mosa (gravatar) Muhammad Mosa said on April 29, 2009

          Yes, you hit the point Dave! I should share this with with all ASP.NET Developers I know and I want them to learn jQuery.
          It is a good introduction for them to understand what exactly they might need.

          Lee Dumond (gravatar) Lee Dumond said on April 29, 2009

          Nice read. jQuery has really opened up a world of browser interactivity to ASP.NET. I’m forwarding this to my few remaining “client-side-phobic” .NET buddies.

          Matt  (gravatar) Matt said on April 29, 2009

          Is it just me or is the color scheme in this site make for a hard read?

          Stacy Spear (gravatar) Stacy Spear said on April 29, 2009

          It is not you Matt. It is a hard read but good content.

          Carol (gravatar) Carol said on April 29, 2009

          Hi Dave, thanks for enlightening other ASP.NET developers on jQuery.. I recently started using it and found that it also nicely with JSON.. I’m glad that .NET 3.5 finally gave us a JSON namespace to work with too. .NET, jQuery and JSON are a great mix (no pun on MIX intended).

          Ashraf Sabry (gravatar) Ashraf Sabry said on April 29, 2009

          Thanks for the good article.

          I wonder how comes that microsoft officially support and use jquery while it already has its javascript framework, the ASP.Net AJAX?

          CodeDigest (gravatar) CodeDigest said on April 30, 2009

          A must to read content for all ASP.Net developers! Thanks Dave!

          Rafael (gravatar) Rafael said on May 08, 2009

          ...and I thought all .NET’s are client-phobic…

          David (gravatar) David said on May 13, 2009

          I fully agree – I have been a professional web developer in the days before the dot com crash, before moving back to mainly desktop work. I’d since tried some other Javascript frameworks, but working with Javascript still seemed like a chore. Until JQuery.
          My latest projects have used JQuery for the client side work, and it’s made the client side code much better to do. If you’ve been scared off in the past by the browser-specific variations and so on, then now is the time to get past that and try again.

          One thing that you didn’t mention, though, is that it also helps make pages which degrade gracefully, or work better with screen readers and the like.

          Mehmet (gravatar) Mehmet said on May 14, 2009

          Very good header and content.

          Prashanth Ganathe (gravatar) Prashanth Ganathe said on May 17, 2009

          Great article, since the availability of plugins are huge its a head ache to choose which is better.
          Today going to try “Glimmer”.

          DNCDude (gravatar) DNCDude said on May 18, 2009

          Nice article. Concise and clear. A while back I wrote a hands on article on getting started with JQuery and ASP.NET. Check it out:

          http://www.dotnetcube.com/post/Getting-started-with-JQuery-in-ASPNET.aspx

          Shasur (gravatar) Shasur said on May 19, 2009

          Hmm… Client programming is always worth a try. jQuery is a good bet

          ZK@Web Marketing Blog (gravatar) ZK@Web Marketing Blog said on June 20, 2009

          Agree, JQuery is an amazing tool. Once I needed to write a huge web project with AJAX technologies while I knew almost nothing about AJAX then (i.e. I’ve never made AJAX sites). I found JQuery and it was a great help! Like you write Li, its wrapper-based syntax, principles and documentation were so simple to learn that I write a raw prototype for main site functions literally in a single day. Definitely recommended tool!

          Sam (gravatar) Sam said on June 28, 2009

          “Beyond that, jQuery UI offers animated transitions between CSS classes and a wide variety of easings. ”

          How exactly is that done? I dont’ see support for it in the animate method.

          Karsten Januszewski (gravatar) Karsten Januszewski said on August 18, 2009

          @sam — assume you mean support for easings? It isn’t the core jQuery library, but is an extension that’s part of jQueryUI. If you don’t want to add all of jQueryUI, you can just add effects.core.js to get the effects. The code then looks like: $(”#plane”).animate({top, “easeOutBounce”, null);

          where easeOutBounce is the effect.

          Glimmer makes using effects pretty simple; I invite you to check it out…

          Lalit Kumar (gravatar) Lalit Kumar said on September 12, 2009

          I had recently take a tour for jquery world and found it realy intresting…
          Evan better then UpdatePanel.

          There is still very less documentation for asp.net developers, i could not found evan a complete sample asp.net application which utilize features of jquery.

          doube in my mind:

          Contradiction between jquery asp.net is jquery perfer client side controls while in asp.net we mostly use server side controls, then how/why MS is merging it in asp.net?

          Does it posible to use both
          updatePanel
          and
          #(”#divPopup”).load(“popup.aspx”).show();

          In my opnion every developer will opt one approach, so why is MS is taking this risk?

          Motorcycle code (gravatar) Motorcycle code said on September 27, 2009

          Its always good to learn tips like you share for blog posting. As I just started posting comments for blog and facing problem of lots of rejections. I think your suggestion would be helpful for me. I will let you know if its work for me too.
          Thanks and keep post such a informative blogs.

          Oliver Mezquita (gravatar) Oliver Mezquita said on November 03, 2009

          Yeap, I think jQuery is one of the best javascript frameworks out there… and very versatile too!

          Brittny (gravatar) Brittny said on February 23, 2010

          Thanks Dave. You made my day.

          I was looking for JQuery info. for asp.net programmer and hung here….

          One Question, do you know site where we can find JQuery examples??? which are easy and for startup….

          Karsten Januszewski Karsten Januszewski said on February 24, 2010

          @Brittny – I’d start with the tutorials at http://docs.jquery.com/Tutorials

          Add your social network profile — we’ll use it to find your avatar. Or, just add your email. That works too.