15 Pragmatic JavaScript Tips for ASP.NET Developers

Here are 15 pragmatic JavaScript tips for ASP.NET developers from my recent presentation at DevConnections 2011 (Las Vegas).

The goal here is pragmatic tips - things you can use right away. Three or four are specific to ASP.NET Web Forms, the rest are pretty cross-cutting and in some cases apply to any web development platform. These are pragmatic tips, not advanced JavaScript development or coding practices, although I did sneak in a bit of SignalR, Node.js, and CoffeeScript at the end. If you're looking for coding practices, I'd highly recommend Elijah Manor's MIX11 talk: Good JavaScript Habits for C# Developers.

Damian Edwards has given a similar talk several times over the past year and kindly shared his samples and advice - his talks are all available here. His talks covered a lot of great information, and my updated talk also included some future / edge stuff, like RIA/JS, Visual Studio 11, ASP.NET 4.5, Node.js, and CoffeeScript. Since I was covering a ton of information in an hour, I opted to structure this talk as a series of 15ish tips, building from the simple and easy material to, well, stuff like SignalR and Node.js with WebMatrix and iisnode.

Slides are here:

I set up a new repo for presentations (slides and code) on Github; here's the sample code for my demos. My presentation wasn't filmed, but Damian's talks at MIX and TechEd were. Links to those videos are in the presentation section of his blog.

Okay, enough talking, more tips. Here we go:

Tip 1: If you’re using Ajax Control Toolkit, get the newest releases

It's been a while since I used the Ajax Control Toolkit, but it's still apparently very popular (substantiated by a show of hands at the presentation). The tip here is that - if you're still using Ajax Control Toolkit - you should be aware that there are regular new releases, and that they're available via NuGet.

Recent releases include several new controls, including Gravatar, Twitter, and a new HTML editor. The new releases also include top fixes from the issues list, and there's a real emphasis on quality - as shown by the automated browser testing with QUnit. You can read more about recent updates on Ajax Control Toolkit from Stephen Walther.

The overall guidance from the ASP.NET team is that they're recommending jQuery for client-side coding. That's where future focus, project templates, code samples, etc., will be. However, if you're using Ajax Control Toolkit, you should be on the latest releases. It's easy to do now, since Ajax Control Toolkit can be installed and updated via NuGet.

Tip 2: Get to know jQuery

Sure, no surprise there. All web developers should know about jQuery, and if you're not using it you should have a pretty good reason. Here are the top advantages I listed:

  1. DOM abstraction
  2. Selector engine (I explained selectors using this Interactive jQuery Selector Tester page)
  3. Plugin ecosystem
  4. Leverage CDN’s (talked about how end users have to wait for your custom scripts to download, while jQuery is very likely cached by their browser)
  5. Included in Microsoft templates (showed that File / New Project will put jQuery in your application)

I pointed out that JavaScript is beautiful and elegant, but sometimes extremely tricky. We looked at variable hoisting as an example. The point is that JavaScript can be a bit tricky, and writing your own libraries when jQuery does it better is an unnecessary code liability to take on.

Tip 3: Install and Update jQuery via NuGet

ASP.NET MVC 3 already includes jQuery as a NuGet package, so it's easy to upgrade when a new version comes out. I showed how to remove the jQuery scripts from an ASP.NET Web Forms application and add jQuery via NuGet to get that same upgrade experience. We looked at adding jQuery plugins via NuGet, too.

Tip 4: Know how to find and use jQuery plugins

I explained what plugins are used for, and showed three great ways to find and use jQuery plugins:

I showed the jQuery theme support, and we hooked up a few jQuery UI datepickers to ASP.NET textboxes.

Tip 5: Use jQuery UI via Unobtrusive Wire-up

Damian's written a nice jQuery plugin to wire up jQuery UI widgets via HTML5 data- attributes, and it works for standard HTML and ASP.NET Web Forms controls. Here's an example:

<asp:TextBox runat='server' ID='startDate'
    data-ui-fn='datepicker' />
<div class='status-box' data-ui-fn='draggable resizable'>
    I'm a Drag and Droppable, resizable content area.
</div>
Joe Stagner has a full walkthrough on this here: Unobtrusive JavaScript in your ASP.NET pages

Tip 6: Write your own jQuery plugins

We walked through turning some of our jQuery code into a plugin, making use of the jQuery Code Snippets for Visual Studio 2010.

Plugins offer some great benefits, even if you never plan to distribute your plugin:

  • Code encapsulation
  • Reuse throughout one site or a number of projects (I talked about an example where my team bundled common jQuery code into plugins, and we were later able to leverage them from content input via CMS users)
  • Standard, tested modularization system that's designed to work well with jQuery

A good way to get started with writing your own jQuery plugins is the Plugin Authoring Tutorial on the jQuery site. It's really well written, starting with simple cases and slowly introducing advanced topics and best practices.

Tip 7: Take advantage of Visual Studio’s JavaScript support

I showed off some of the JavaScript editing and Intellisense features that are included in Visual Studio 2010. A lot of people aren't aware that the Intellisense infers type and can handle dynamic variables, loops, etc. Neat stuff.

See Scott Guthrie's post, JavaScript Intellisense Improvements with VS 2010, for a nice walkthrough.

Tip 8: Get ready for Visual Studio 11 JavaScript features

Okay, Visual Studio 2010 has some nice JavaScipt editing features, but Visual Studio 11 Developer Preview is a huge advance here. It's actually using the same engine that's used in the Internet Explorer Developer Tools, and Visual Studio 11 adds a lot of goodness like implicit references (configurable by editing a JavaScript file), brace matching, outlining, etc.

More on those features here: http://bit.ly/vs11javascript

Since Visual Studio 11 Developer Preview works side-by-side with Visual Studio 2010, you can start using those features today. Yes, it's pre-release, but I'll give it the Works On My Machine certification - I've been using Visual Studio 11 Developer Preview side-by-side with Visual Studio 2010 since //build and it's been working great. Visual Studio 11 Developer Preview starts up so quickly, I'm often using it in cases where I would have used Notepad++.

Tip 9: Use the Visual Studio 2010 JScript Editor Extensions

Ah, you say, Visual Studio 11 Developer Preview is neat, but that's not what I call pragmatic. It's not out yet!

Fine, there are some great Visual Studio extensions which give you a lot of the great features in Visual Studio 11 in Visual Studio 2010. That's no accident, some (like the Web Essentials extension) are written by the PM's who are driving the Visual Studio 11 features.

The Visual Studio JScript Editor Extension adds a lot of the Visual Studio 11 JavaScript editing goodies to Visual Studio 2010. Things like:

  • Brace Matching
  • Outlining / Code Folding
  • Current Word Highlighting

Is this pragmatic? Sure! It's a free, quick install, and if you do any JavaScript editing in Visual Studio it will pay for itself in no time!

Tip 10: Use ASP.NET 4 ScriptManager features

Okay, if you're using ASP.NET 4.0 Web Forms, you need to know about the new features in ScriptManager. In my talk I demo'd how easy it is to use CDN's and how to register scripts like a Ninja Pirate Honey Badger with ScriptManager.ScriptResourceMapping. Script Resource Mappings offer a number of benefits:

  • You can register a library like jQuery by a version independent name ("jQuery"), so upgrading jQuery versions means that you only need to update the mapping in one place, rather than throughout your code
  • Using Script Resource Mappings really helps in cases where you may be referencing a library multiple times (e.g. in a page and in a multi-instance user controls within that page) since it will only include the script once

Pragmatic? Yes! This shipped with ASP.NET 4.0 (April 2010), and taking advantage of resource mappings and automatic CDN usage means you'll have more maintainable, higher performing, better script references with minimal effort.

Tip 12: Use RIA/JS for WCF services

RIA/JS is a set of jQuery plugins for accessing RIA Services DomainService and OData services. My demo - for this (which was unfortunately pretty rushed) covered the BigShelf sample from the RIA/JS team, which shows how you can use WCF RIA Services to access WCF services from a browser using a really efficient JavaScript library. It includes full featured services, and your service calls are all using really light-weight JSON.

The best way to get up to speed on what's new - and coming - in WCF RIA Services is to watch Dinesh's talk at BUILD. Jeff Handley posted a good summary of the updates for //build which explains what's been released and what's in the works. The short summary is that if you're calling into WCF services from the browser, you should strongly consider using RIA/JS (Mea culpa).

Tip 13: Use SignalR for long-polling

Yeah, this is tons of fun. SignalR is a "smart" way to do long-polling with ASP.NET. For an example, I ran the StackExchange chat application and showed that each request was polling - sending a bunch of repetitive requests to the server, asking "Anything new? How about now? Now? Anything? Hey, anything new?"

HTTP Short Polling

SignalR is a nice system (both client and server libraries available) which implements long polling, in which the browser makes a request and the server waits to respond (keeping the connection) open until there is new information to send to the client.

HTTP Long Polling with SignalR

You could implement this pattern on your own if you worked at it, but there's a good chance you'd be tying up threads on the server for each open request. Some smart guys on the ASP.NET team have set up this library to leverage stuff like the task parallel library, websocket support (if the browser supports it), takes advantage of async / await, etc.

Is this pragmatic JavaScript? Absolutely! This is real, working code, you can install SignalR immediately via NuGet, and it improves scenarios in which the client is waiting for updates from the server because it's more performant and will return information to your clients immediately, rather than waiting for the next time they poll. The source includes some great samples, including some multi-user applications like chat and a collaborative shape / drawing example.

You can find out more in Scott Hanselman's recent post, Asynchronous scalable web applications with real-time persistent long-running connections with SignalR.

Tip 14: Server-side JavaScript with iisnode and Node.js

Node.js is a popular system for writing server-side code in JavaScript, and it's optimized for high performance and asynchrony. I wrote a big post on it recently: Using Node.js in an ASP.NET MVC application with iisnode.

Is this pragmatic? Well, this one is stretching things a bit, but I couldn't help myself. You can use Node.js in IIS using iisnode (even integrating it into an ASP.NET site, since iisnode runs as a standard IIS handler), and it works today. The Node.js community is big, and there are a ton of great packages available now. Is it likely people will start integrating Node.js into their ASP.NET Web Forms applications any time soon? Hard to say. One advantage is that you can reuse JavaScript code on client and server, which could be a big advantage if done right.

Tip 15: Adventurous? Keep an eye on CoffeeScript

Early on, I talked about the fact that JavaScript is powerful, but can be a bit tricky. Some of this is due to the fact that JavaScript is a dynamic, prototype based, weakly typed language masquerading under Java syntax. CoffeeScript is a "little language" that compiles into JavaScript:

Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

One benefit of CoffeeScript is that it automatically prevents you from accidentally shooting yourself in the foot due to strange language quirks. If you're writing a lot of JavaScript, CoffeeScript is definitely worth a look. I recently wrote An introduction to CoffeeScript which explains how it works and how to get started.

What about you?

Okay, that's my list. Got any tips you'd like to share?

5 Comments

  • Tip #16: Get SASS and Compass. Your CSS will be SO much better and easier to organise. You will need to install Ruby if you want Compass with your SASS; but if not the Web Workbench plugin for VS gives you straight SASS.

  • On Tip 12: Use RIA/JS for WCF services:

    You ever try to configure your wcf service to be REST. Then you can just hit it from jQuery Ajax stuff. I got it working on a couple personal projects. Can also do jsonp (with some more work).

    various articles posted on the nets about it.

    Cheers

  • The asp.net world is getting pretty far behind here. Here's what I'd recommend for anyone, regardless of programming environment (I do both)

    1. jQuery, which is only the bare minimum price of entry these days
    2. Coffeescript. Don't ever ever write any more javascript. Coffeescript is half the length, and enforces better code practices.
    3. Underscore.js
    4. Either BackboneJs or KnockoutJS, both really
    5. Stop making anything but restful services that return JSON. Seriously. Your life will be so much easier. Then just handle your ajax calls w/ jquery, Backbone, or Knockout.
    6. Test your javascript with Jasmine BDD
    7. I'd skip jquery extensions, because they should really only be for view-only code, and if you haven't found something that does what you want, you probably just haven't looked hard enough. There's value in separating code out, but once you have a framework behind you, you'll have far better options. By framework, I mean something like Backbone. Jquery is still just for the UI.
    8. Remember that once you reach a certain level of complexity, your javascript is real code. The same best practices apply there as they do in your c#. (Separating your view logic etc)

  • Great article post. Much obliged.

  • Hello, its nice post about media print, we
    all know media is a fantastic source of data.

Comments have been disabled for this content.