jQuery for the ASP.NET Developer
There are dozens of separate posts here describing various approaches ASP.NET developers can use to make effective use of jQuery. Whether you want to layer a simple UI effect onto an existing WebForms application or you want to architect a completely jQuery-centric application, there’s a decent chance I’ve written about it here at one point.
Unfortunately, finding your way through all of those posts isn’t always as easy as it should be. Worse, it’s all too easy to find your way to one post that begins to cover a topic, but not realize there are several subsequent posts that would leave you with a much more complete understanding of the topic.
So, I created this page to combat that problem. It attempts to organize those posts into a more coherent narrative than a search engine can hope to provide. My intent is to continually update and improve this page over time, so please do get in touch with me with any feedback you have.
Curiosity: Augment traditional ASP.NET pages with jQuery
One of the easiest ways to augment an ASP.NET application with jQuery features is to layer them on top of the functionality that ASP.NET already provides.
Faking it: UpdatePanels
The UpdatePanel is inefficient, but it’s a tool that has enjoyed significant adoption despite its drawbacks. Though its server-centric approach to AJAX places limits on the level of interactivity you can achieve, it’s possible to layer some of jQuery’s niceties on top of an UpdatePanel by using the client-side events that ASP.NET AJAX exposes when you add a ScriptManager and UpdatePanel to your pages.
For example, you can use a modal popup plugin like BlockUI to display progress indication to your users while an asynchronous PostBack is in progress. Following from the progress indication, you can use the same events to provide nicer feedback after async PostBacks have completed as well. ASP.NET AJAX does provide a control to do something similar, but using jQuery gives you access to a wider range of prepackaged functionality and polish.
jQuery and ASP.NET can play well together
It’s a common misconception that ASP.NET is limited to generating markup too sloppy to easily use client-side libraries against. Though it’s certainly possible to use WebControls that generate embarrassingly bad HTML, ASP.NET is just as capable of outputting clean pages that are easy to extend on the client-side.
One of my older posts has an example of doing just that, using an ASP.NET Repeater and a handy jQuery plugin called quickSearch. The result is nothing groundbreaking, but it’s a simple example of how to layer jQuery onto a databound ASP.NET control.
Using jQuery Validation instead of ASP.NET’s
Once you’re accustomed to using the jQuery Validation plugin on the client-side, going back to ASP.NET WebForms’ server-centric approach to validation isn’t an attractive option. Sure, ASP.NET’s validation controls do provide rudimentary client-side feedback, but that doesn’t compare to the control that jQuery Validation offers.
Unfortunately, plugging jQuery Validation into a WebForms page isn’t entirely straightforward due to WebForms’ being architected around a single form per page. Some time ago, I came up with a workaround approach for making jQuery Validation work with a WebForms page anyway.
A side-effect of WebForms’ single-form architecture is that the concept of validation groups is necessary, so that separate portions of the form can be validated independently even though there’s only a single form to submit. However, you can still use jQuery Validation to emulate ASP.NET’s validation group paradigm.
Interest: Bridge the gap between client and server
Eventually, using jQuery to add superficial enhancements isn’t enough. Searching for a direct bridge between jQuery and ASP.NET is a natural next step for websites and applications of any significant complexity.
In the beginning there were ScriptServices
One of my simplest examples of that involves using jQuery’s
$.ajax() to communicate with an ASMX “ScriptService” purely in JSON. That post alone is enough to get up and running, but it only covers a very basic scenario. If you intend to put that approach to work in real-world applications, there’s more you’re going to want to understand.
A page method detour
Soon after that post about communicating with ASMX services, I found that the same approach also worked for communicating with ASP.NET’s “page methods”. As simple as the ASMX approach is, page methods are even more appealing to many since you can define them right on the page that will call them. However, that can also lull you into a false sense of security, because there is no mechanism that requires page methods be called from the page where they’re defined.
Let ASP.NET handle the tedium for you
One of the mistakes you’re most likely to make when you’re getting started with ScriptServices and page methods is manually intervening in the serialization process. Since it’s well-known that JSON is the preferred transfer format, it’s natural to assume that you probably need to do something in order to achieve that.
However, ASP.NET will handle converting to and from JSON entirely automatically. As long as you follow the correct convention when making your AJAX calls, everything else will be handled for you transparently.
ASP.NET automatically defends your data… and breaks your code
Regardless of which approach appeals to you, there are a few techniques that will improve your development experience. First, it’s important to understand the
.d that ASP.NET 3.5 introduced into all of its JSON responses. I also wrote about a few ways to normalize away the
.d so that the same client-side code works against ASP.NET 2.0 and ASP.NET 3.5+, but that really isn’t a very common requirement these days. The important thing is to understand that the
.d is present (and optionally to understand why it’s a useful feature).
A few troubles you may run into when sending JSON to ASP.NET
Not only do these handy communication features respond with JSON formatted data, but they also expect you to send JSON formatted data to them. That can be tricky at first, because it goes (very) slightly against jQuery’s grain. One of the most common errors you’ll encounter when sending data for the first time is the fairly nondescript “Invalid JSON Primitive” error, which occurs when you fail to send a JSON string as the AJAX request’s data parameter.
Once you’ve mastered that nuance, there probably aren’t any more “gotchas” remaining. However, building strings of JSON interspersed with your client-side data becomes very unwieldy in a hurry. A much better alternative is to use data transfer classes (also known as ViewModels) on the server-side that match up to client-side data structures and let ASP.NET handle the translation for you automatically.
Simple is better
As it turns out, I slightly over-complicated the
$.ajax() call syntax in my original posts about calling ASP.NET services with jQuery. Though using the usual Content-Type of
application/json; charset=utf-8 works fine, that entire string isn’t necessary. Further, as long as you’re using a later version of jQuery, specifying the dataType parameter to
$.ajax() isn’t necessary either; jQuery will automatically detect that based on the response’s Content-Type and parse accordingly.
Building bridges (across domains)
One of the measures that browsers take to protect users against malicious sites is restricting XMLHttpRequest to communication only with the same “origin” that the page it’s running on came from. Unfortunately, that security precaution often thwarts benign requests you might want to make to services simply running on different ports or subdomains.
There are three basic approaches to working around this problem:
JSONP – If the service you want to request across domains supports JSONP, that’s one commonly employed option. Unfortunately, the JSONP approach isn’t capable of anything beyond a simple GET with querystring parameters. Obviously, that’s not suitable for use with the services described above since they require a POST request.
CORS – CORS (Cross-Origin Resource Sharing) is a great option if you don’t need to support IE9 or earlier. In Chrome and Firefox, using CORS with ASP.NET services is as easy as adding two lines of XML to your web.config. Over time, this will become the standard approach for cross-domain AJAX work. Unfortunately, it’s going to be a while before we can support only IE10 and later.
Proxy – The best of both worlds (i.e. the compatibility of JSONP and the flexibility of CORS) is proxying the request through a same-origin middleman of your own. One example of that is to use an ASP.NET HttpHandler that relays requests between client and remote server. The drawback of that approach is that the middleman adds latency to the request, but sometimes that’s a price worth paying.
Embrace: jQuery-centric UIs powered by ASP.NET
Eventually, it’s only natural to realize that the UpdatePanel’s up-front convenience just isn’t worth the amount of performance that it costs.
Coming soon: Index of posts using jQuery + templating to render server-side data retrieved via services.