Save yourself some typing when you call ASP.NET services
ASP.NET, jQuery By Dave Ward. Updated December 28, 2011Note: This post is part of a long-running series of posts covering the union of jQuery and ASP.NET: jQuery for the ASP.NET Developer.
Topics in this series range all the way from using jQuery to enhance UpdatePanels to using jQuery up to completely manage rendering and interaction in the browser with ASP.NET only acting as a backend API. If the post you're viewing now is something that interests you, be sure to check out the rest of the posts in this series.
Mea culpa: I may owe your fingers an apology.
If you’ve been using my approach for directly calling ASP.NET’s JSON-based services with jQuery, you know that specifying the correct Content-Type on your requests to them is a crucial part of coaxing JSON out of them. However, when I suggested that a Content-Type of application/json; charset=utf-8 was necessary, that was overly specific.
Charset=who-cares
As it turns out, only the application/json portion is necessary.
More accurately, ASP.NET checks that your request’s Content-Type header begins with application/json. Beyond that, you can even specify a charset of acrobatic-unicorns and it still works (no, really; I tried).
That may only sound like a minor reduction in typing, but I find that it makes a non-trivial improvement in how memorable the parameter is. At least for me, the punctuation in ; charset=utf-8 made that Content-Type string tedious to remember and I would often resort to copy/paste to be sure that it was correct.
It’s nice to be able to quickly type out an $.ajax() call to your services without tedious memorization, online reference, or copy/paste.
Bonus: Ditch the dataType
When I originally wrote about using jQuery with ASP.NET’s web services, the current jQuery version was 1.2 and jQuery’s $.ajax() method looked nothing like what it does today. One of the changes that occurred over the years is that jQuery 1.4 added support for parsing responses based on their Content-Type.
Before that addition, it was imperative that you specify a dataType of json if you wanted jQuery to automatically handle converting JSON responses to JavaScript objects. Beginning with version 1.4, responses with the Content-Type application/json are automatically treated as JSON and parsed accordingly.
Since ASP.NET does set the correct Content-Type on its JSON-serialized responses, manually specifying a dataType is no longer necessary as long as you’re using jQuery 1.4 or later.
So, what’s left?
Eliminating all that dead weight, your AJAX calls to ASMX ScriptServices, Page Methods, and WCF services can now be simplified to this:
$.ajax({ url: 'Service.asmx/Method', type: 'POST', contentType: 'application/json', data: '{"Parameters":"Must be JSON strings!"}', success: function(response) { // Don't forget that the response is wrapped in a // ".d" object in ASP.NET 3.5 and later. console.log(response.d); } });
Sometimes it’s the little things…
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.



If you have many AJAX calls and want to save further typing, you could also use jQuery.ajaxSetup(): http://api.jquery.com/jQuery.ajaxSetup
For example, you could set up the following to be used on all subsequent AJAX calls:
The example above would then become the following:
One thing to watch out for when setting the global default to POST is that plugins which use $.ajax() to make implied GET requests may break. I’ve run into that with jTemplates’ remote template loading feature and a couple autocomplete plugins.
Good to know, thanks Dave.
Since I’ve made these minor changes the success(response) is now null. Weird. Any ideas.
Which version of jQuery are you using? In 1.5 and later, it’s a little more tricky to get the dataFilter approach working. Some talk about that and solutions here on this post’s comments: http://encosia.com/jquery-1-5s-ajax-rewrite-and-asp-net-services-all-is-well/#comments
This is a side issue but I found it whilst working on this change. When you upgrade to jquery 1.6.1 form 1.3 the jtemplates no longer work. Have you seen this problem before Dave? The error seems to be on this line
$(‘#AccountsList’).processTemplate(response);
Error: Uncaught TypeError: Cannot read property ‘length’ of null
This works fine the moment I switch back to the older version of jQuery.
Thanks
Jon
Do you have the same trouble in 1.4 or 1.5? If it’s unique to 1.6, that’s probably related to the .attr() change.
I’ve mostly moved to jQuery Templates for client-side templating now, so I haven’t done a lot of compatibility testing with jTemplates in 1.5 and 1.6. If you can narrow it down and come up with a barebones sample that reproduces the error, email it to me and I’ll take a look. jTemplates ultimately isn’t super complicated, and that probably wouldn’t be difficult to fix.
I’ve jumped straight to 1.6.1 so missed a few!
I might have a go at those jquery templates as it seems the jTemplates are no longer being developed so it’s likely issues will increase.
Thanks for your reply Dave
Jon
Nice update, Dave. Thanks for keeping us on top of the evolving situation.
For the lazy like me, when you’re just calling GET and expect JSON, like when you’ve set up a simple WCF service, i usually fall back on jQuery.getJSON(). There just aint nothing to it.
$.getJSON(‘http://server/services/test.json’, function(data) {
console.log(data.d);
});
It’s dead simple to use with JSONP as well, which is pretty nice, just add the “?callback=?” to the url and you’re set.
Thanks for the update Dave. Keep it up.
Rather than having to copy/paste this content type over and over wouldn’t it make sense to simply abstract it away into a method in some common framework? – perhaps even as a jQuery extension. Would be trivial (yet very helpful!) to do so.
Just a thought :-)
hi Dave,
Thanks a lot for the update. i’ve been using your methods to POST via jquery AJAX for a while now. this is really useful.
Regards,
Alex
Thanks for the update Dave!
Good tip Dave.
Sending JSON request in ASP.NET MVC seems to be dangerous now,
http://weblogs.asp.net/imranbaloch/archive/2011/05/23/security-issue-in-asp-net-mvc3-jsonvalueproviderfactory.aspx
i love all your posts. If a browser has javascript disabled will jQuery work??
Thanks.
No, jQuery cannot function if JavaScript is disabled. jQuery itself is just a library written in JavaScript.
Thx for the quick reply!
I don’t get. Your request sets content type to JSON. But the answer is XML containing HTML. Where is the JSON structure?
The request’s content type only applies to the request itself. The response will have its own content type.
In the case of ASP.NET’s ScriptServices and page methods, the response will be JSON as long as you call it via a POST request with content type application/json.
Thanks for the quick reply. That makes sense.
Exactly where and how dose the reply get wrapped in “.d”?
The
.dis a security feature that ASP.NET automatically adds to its JSON responses, beginning with ASP.NET 3.5. You can read more about that and why it matters here: http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/