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.

One Mention Elsewhere

  1. D-Blog » Blog Archive » jQuery for a ASP.NET Developer

8 Comments

9:34 am - February 28, 2012

Thanks for this, mate. Your posts are really awesome and this assemble was more than necessary :)

Reply to this comment
5:15 am - May 10, 2012

i am new to jquery, but your blogs helps me alot.Thanks for sharing knowledge with us.

Reply to this comment
7:14 am - May 17, 2012

I’ve used your posts a lot, and find them to be very helpful. One problem I always run into is that I end up being stymied by the fact that webmethod routines have so little access to the real guts of the page because they have to be static. Maybe I’m missing something, but I am quickly coming to the conclusion that webforms and using javascript for anything truly powerful just doesn’t work. Am I missing something?

Reply to this comment
11:26 am - May 22, 2012

When I began writing these posts, I was using WebForms and found ways to make it work (because I had to; there was no MVC at that time). The key is to abandon the server-centric mindset and avoid trying to do something like access the Page’s controls from within a page method.

Instead, take a client-centric approach. For example, gather the values you need on the client-side and send them along with the request. Similarly, you can set the value of those controls on the client-side when the response comes in. It turns out not to be much more work than the old WebForms, server-centric approach, but the performance boost is huge and you get a great deal more control over the client-side UX.

Reply to this comment
Hemima Subscribed to followup comments
12:24 am - December 3, 2012

This is an awesome article please keep on post this kind of post, am very much thankq ful to this article

Reply to this comment
jkearney486 Subscribed to followup comments
3:27 pm - January 11, 2013

I wanted to thank you for all these posts on integrating ASP.NET with jQuery, they’ve helped me improve the projects I’ve worked on a lot.

I’m a relatively new developer (less than a full year of experience), who started out with ASP.NET web forms. Between using the tips and tricks listed here and a bit of knockoutjs, I feel like I’ve really made some great improvements over what I had been using (UpdatePanels with full page postbacks).

However, I feel like now that I’ve gone down this route, I’m missing the point, so to speak, of ASP.NET web forms. My code behind for my current project looks like a Page_Load and a bunch of Web Method functions called via jQuery Ajax. I’m wondering if I should be looking into moving over to MVC. I’ve already walked through a tutorial and it seems like a great framework with much better interaction between ASP.NET and Javascript. I’d like to learn MVC, and have a basic understanding the underlying design concepts from using knockoutjs. But I’m still far from being a pro at ASP.NET web forms yet, so I’m concerned I’m ‘abandoning’ it too early without fully understanding it.

I know there’s no simple answer to “which framework should I be using?” but I wanted to get your thoughts on this.

Reply to this comment
7:48 pm - January 11, 2013

Personally, I haven’t been using WebForms for new projects since about the time MVC 2 shipped. A lot of my posts about using jQuery with WebForms came before MVC was released, so they were more about making WebForms an environment I could enjoy than they were about promoting WebForms as the best solution. If you’re comfortable with the closer-to-the-metal approach that my AJAX/jQuery posts and most MVC work entails, MVC is probably the better framework for you.

Reply to this comment
jkearney486 Subscribed to followup comments
12:15 pm - January 14, 2013

I’ve been getting more comfortable with the Ajax/jQuery and knockoutjs approach I’ve been using, so I think I’ll look into MVC further. Thanks, I appreciate the response.

Reply to this comment

Leave a Reply

Basic HTML is allowed (e.g. <a>, <blockquote>, <strong>, <em>, etc).

To post formatted code blocks, use <pre lang="x">code</pre>, where x is asp, csharp, html, javascript, or xml.