Scott Hanselman

jQuery to ship with ASP.NET MVC and Visual Studio

September 28, 2008 Comment on this post [60] Posted in ASP.NET | ASP.NET MVC | Javascript | Microsoft
Sponsored By

I've done a series of four podcasts dedicated to JavaScript over the last month. Why? Because of this rockin' sweet announcement:

Microsoft is going to make jQuery part of the official dev platform. JQuery will come with Visual Studio in the long term, and in the short term it'll ship with ASP.NET MVC. We'll also ship a version includes Intellisense in Visual Studio.

The Announcement Blog Posts

This is cool because we're using jQuery just as it is. It's Open Source, and we'll use it and ship it via its MIT license, unchanged. If there's changes we want, we'll submit a patch just like anyone else. JQuery will also have full support from PSS (Product Support Services) like any other Microsoft product, starting later this year. Folks have said Microsoft would never include Open Source in the platform, I'm hoping this move is representative of a bright future.

jQuery Intellisense

Visual Studio 2008 has very nice JavaScript intellisense support that can be made richer by the inclusion of comments for methods in 3rd party libraries. Today you can search the web and find intellisense-enabled jQuery files hacked together by the community, but we intend to offer official support for intellisense in jQuery soon.

 image

JQuery is really complimentary to MS-Ajax. For example, we had been talking about writing CSS-Selector support, but figured, jQuery does it really well, why not just use it?

JavaScript Libraries Play Well With Others

I wanted to put together a little demo application that used jQuery to spice up a talk I've given on ADO.NET Data Services. The app would retrieve some data from a Bikes database, and would have some radio buttons to change the color queried.

The whole application is a single static page. There's no code-behind and the only server-side work is the data retrieval from SQL. However, the concepts could be applied to ASP.NET WebForms or ASP.NE T MVC.

Here's a one page app using:

  • ADO.NET Data Services and it's JavaScript Client Library
  • ASP.NET AJAX
  • ASP.NET AJAX Client Templating (Preview)
  • jQuery 1.2.6

It looks like this:

image

Here's what's going on underneath. First, I'm retrieving data from SQL Server and I need it in JSON format. I'm  using the AJAX Client Library for ADO.NET Data Services to make a REST (GET) query to the back-end. To start with I'll just get the data...I include "datatable.js" as a client-side script and use Sys.Data.DataService() to make an async query. In JavaScript you can tell it's a Microsoft type if it's got "Sys." front of it.  All the client support for ADO.NET Data Services is in datatable.js.

I'll be getting back dynamically created JSON objects that look just like my server-side data. In the query I'm asking for the top 5 results given a color.

BTW, the first line of LoadBikes() is a little JavaScript syntax that says "if q isn't there, then make a q that equals "Red."

<script type="text/javascript" src="Scripts/DataService.js"></script>    
<script type="text/javascript">
var bikes;

Sys.Application.add_init(function() {
LoadBikes();
});

function LoadBikes(q) {
q = q || "Red";
var svc = new Sys.Data.DataService("bikes.svc");
svc.query("/Products?$filter=Color eq '" + q + " '&$top=5", OnProductsLoaded);
}
...

When I get back the results from the asynchronous query call, I could use string concatenation with the ASP.NET AJAX Sys.StringBuilder type to build HTML on the fly like this:

var html = new Sys.StringBuilder("<ul>");
for (var i = 0; i < result.length; i++){
html.append("<li><div class=\"bikerow\">");
html.append("<img src=\"bikes.svc/Products(" + result[i].ProductID + ")/Photo/$value\">" + result[i].Name + " " + result[i].ListPrice);
html.append("</div></li>");
}
html.append("</ul>");
$get("tbl").innerHTML = html.toString();

There's MANY ways to get the exact same results in JavaScript when you introduce different libraries. There's tradeoff's between size, speed, maintainability, and your happiness. It's nice to pick and choose.

Rather than using StringBuilder, I'll use the new (preview) ASP.NET AJAX 4.0 Client Template stuff from BLR, Dave Reed, Boris Rivers-Moore and Nghi Nguyen. This is more declarative and easy to maintain way to accomplish the same thing.

<div id="bikes" class="sys-template">
<ul>
<li>
<div class="bikerow">
<img sys:src="{{'bikes.svc/Products(' + ProductID + ')/Photo/$value'}}"/>
{{Name + ' ' + ListPrice}}
</div>
</li>
</ul>
</div>

This is a declaration of what I want the table to look like with {{ binding expressions }} in curly braces. The img src= is an ADO.NET Data Services HREF to a product image in the database like "/bikes.svc/Products(740)/Photo/$value" that returns an image directly.

I'll add ASP.NET AJAX's JavaScript library along with the Preview Templates script from CodePlex:

<script type="text/javascript" src="Scripts/MicrosoftAjax.debug.js"></script>
<script type="text/javascript" src="Scripts/MicrosoftAjaxTemplates.debug.js"></script>

Then, when things are initialized, I'll $get() that template and make a Sys.UI.DataView and store it in a variable called "bikes" and when asynchronous call returns, I'll take the array of data from result and apply it to the DataView.

<script type="text/javascript">
var bikes;
Sys.Application.add_init(function() {
bikes = $create(Sys.UI.DataView, {}, {}, {}, $get("bikes"));
LoadBikes();
});
...
function OnUsersLoaded(result){
bikes.set_data(result); ...

Now, I'll start leaning heavily on the jQuery library to change the background colors of just the even-numbered items in my list. I'll also add 100ms animation that draws a border and increases the font size of the item the mouse is over. Notice the "chaining" of the functions as I modify the div. Each method returns the jQuery object so you can increase fluency with chaining as much as you like. I'll also use jQuery to easily setup a group of click events on the radio buttons.

The complete hacked-together code is this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Friggin' Sweet</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Scripts/MicrosoftAjax.debug.js"></script>
<script type="text/javascript" src="Scripts/MicrosoftAjaxTemplates.debug.js"></script>
<script type="text/javascript" src="Scripts/DataService.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.2.6-intellisense.js"></script>
<script type="text/javascript" src="Scripts/DataService.js"></script>
<script type="text/javascript">
var bikes;
Sys.Application.add_init(function() {
bikes = $create(Sys.UI.DataView, {}, {}, {}, $get("bikes"));
$(".colorfilter").click(function(e) {
LoadBikes($(this).val());
});
LoadBikes();
});

function LoadBikes(q) {
q = q || "Red";
var svc = new Sys.Data.DataService("bikes.svc");
svc.query("/Products?$filter=Color eq '" + q + " '&$top=5", OnProductsLoaded);
}

function OnProductsLoaded(result) {
bikes.set_data(result);

$("ul li:even").css("background-color", "lightyellow");
$("ul li").css("width", "450px").css("font-size", "12px");

$("div.bikerow").mouseover(function(e) {
$(this).animate({
fontSize: "18px",
border: "2px solid black"
}, 100);
}).mouseout(function(e) {
$(this).animate({
fontSize: "12px",
border: "0px"
}, 100);
});

}
Sys.Application.initialize();
</script>
</head>
<body xmlns:sys="javascript:Sys">
<form id="form1" runat="server">
<input type="radio" class="colorfilter" name="color" value="Red" />Red
<input type="radio" class="colorfilter" name="color" value="Silver" />Silver
<input type="radio" class="colorfilter" name="color" value="White" />White
<input type="radio" class="colorfilter" name="color" value="Multi" />Multi
<input type="radio" class="colorfilter" name="color" value="Black" />Black
<div>
<div id="tbl">
</div>
<div id="bikes" class="sys-template">
<ul>
<li>
<div class="bikerow">
<img sys:src="{{'bikes.svc/Products(' + ProductID + ')/Photo/$value'}}" />
{{Name + ' ' + ListPrice}}
</div>
</li>
</ul>
</div>
</div>
</form>
</body>
</html>

And it looks like this. Notice that I've got FireBug open and you can see three AJAX calls via ADO.NET Data Services with different queries. I'm hovering the mouse over the second bike, so its font is larger it has a border.

 image

All of the scripts getting along happily. My code clearly sloppy, but this is a good example of how jQuery provides functionality that the Microsoft libraries don't. Things are better when the libraries are used together. JQuery complements ASP.NET, ASP.NET AJAX and ASP.NET MVC nicely and jQuery already has a large following within the .NET community. That's why we're going to ship, support and promote jQuery in ASP.NET, ASP.NET MVC and Visual Studio going forward.

This was a simplistic example and I'm sure you've got better ideas, so I'd encourage you to go around the Net and get involved in the dynamic jQuery community. If you've used jQuery on an ASP.NET site, sound off in the comments.

JQuery Resources

Hanselminutes JavaScript Podcast Series

* Thanks to Pablo Castro for his Bike database and ongoing help. Big thanks to Scott Koon for helping me debug my demo at 2am this morning using CrossLoop while kindly not asking what I was working on. Also thanks indirectly to Rick Strahl for his excellent .NET (and often jQuery) blog.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
September 28, 2008 22:40
Wow! This is a great news! [Doing happy dance!]

We could not use jQuery at my current project because it is 'open source'. Now that Microsoft officially supports jQuery, it's time to go back to the management and get the permission to use jQuery! Thank you!

September 28, 2008 22:58
This is really exciting. Good choice on Javascript libraries.

Chris Sutton
September 28, 2008 23:03
Awesome! I've just started out on using more and more jQuery on a new project, putting together little scripts for existing stuff and teaching our devs how they can use it. And it's been such a great tool..
Very happy to see it shipped by MS.
September 28, 2008 23:26
Excellent news and excellent choice of JavaScript library. jQuery is really the best there is. A little nit about your examples, though: the 'language' attribute has been deprecated and not required for 10 years or so. Time to let it go! :-)
September 28, 2008 23:33
And this is the part where I go "OMGOMGOMG!" and run around the room all happy like. This is fantastic news! I've been lobbying to use jQuery on my little slices of microsoft.com since I started working here and am hoping this news will help!
September 28, 2008 23:35
asbjornu - Ha! I'm old. Fixed. Thanks!
September 28, 2008 23:44
Very cool - I've done some jQuery and ASP.NET MVC work and they work really well together. One thing that I'd really like to see ASP.NET MVC strive for is unobtrusive javascript and really push developers to have a clean separation of presentation (css), document (html) and behavior (js). A lot of web developers understand the need for separation of layers on the server, but most that I meet don't bother once the bits have been pushed down to the client.
September 28, 2008 23:52
This is fantastic news!! Thank-you MSFT!! And thanks to Scott for the links.. :)

@Scott, when are you doing a podcast with Douglas Crockford?
September 28, 2008 23:53
Wow, that is great & very unexpected news!

September 29, 2008 0:04
Ugh, your blog engine just ate my comment somehow, landed on the error page. Let me try again.

This is really great news! But am I missing something, or does this represent a significant shift in terms of Microsoft policy regarding integration of open source products into the .net platform? I don't mean to sound snarky, but if you had asked me to guess whether a) jquery was to be made an official part of the .net platform or b) microsoft were writing their own 'mquery', I would have guessed that the latter was more likely. Is there an existing precedent that I've missed or is this really as big a deal as I think it is?
September 29, 2008 0:04
Nice. Using ASP.NET MVC has got me working with HTML/JavaScript more extensively than I have since the days of classic ASP. The maturity of the JavaScript libraries makes things that used to be horrific to code a snap. I had settled on jQuery as my general purpose library, due to its consistent awesomeness. Microsoft's commitment to jQuery promises to make it even better.

The move totally makes sense. I'm glad to see that it didn't go the way of, say... MSTest. I'd love to see Microsoft continue to put its heft behind some of the great open source projects. Not just because of the wins in functionality, but because of the fact that it will allow new tools into shops that won't use anything, unless it's officially blessed by MSFT.
September 29, 2008 0:24
This is amazing, awesome news. Blessed be JQuery and all that it provides.
September 29, 2008 0:25
This announcement is definitely exciting, but the example above worries me. Anyone who's read Steve Souder's excellent book "High Performance Web Sites" will agree that the correct place to insert JavaScript is at the bottom of the page.

Will ASP.NET AJAX 4.0 allow that, Scott?
September 29, 2008 0:31
This is some of the best development news I've heard in months. Kudos to everyone at Microsoft who made this happen.

I've got an ongoing series of posts dealing with several aspects of using jQuery with ASP.NET, which will probably be useful for any ASP.NET developers new to jQuery: http://encosia.com/category/jquery/
September 29, 2008 0:37
- qq= q|| "Red";
+ q= q|| "Red";
Tim
September 29, 2008 1:22
This is great news, and a bold move, no doubt that jQuery is the best JS library ever built, and with Microsoft PSS support & ASP.net integration, it just make it the perfect marriage.
September 29, 2008 1:28
You could knock me over with a feather. This is an amazing announcement. Even more significant than having explicit support for jQuery is the milestone inclusion of a "not invented here" technology in a distribution. Kudos!
September 29, 2008 1:28
Great news. I use jQuery on every ASP.NET project.

So the approach for templating is becoming clearer, with client side templates, which I certainly like the look of. I'm now keen to see the direction for client side validation (which I'm sure is not far away, with recent ModelState and HtmlHelper additions) and widgets (I assume a firm approach for these will be longer in coming).
September 29, 2008 1:30
Scott,

I'm sure Microsoft has a lot of library in Microsoft Ajax Library that you can use to accomplish the same thing in your demo. I know that Microsoft Ajax Library has been written primarily to support the 'server-side' Ajax interaction with Ajax Control Toolkits. However, now Microsoft seems to make balance between 'server-side' and client side web programming models with the 'soon to be released' ASP.NET MVC.

What's general recommendation then? I mean what the best toolset to accomplish one kind of web programming model? I know we can mix js library over the other but you know, including two libraries will add the size of downloaded files.
September 29, 2008 1:32
This is huge. I never expected this... It's good to have jQuery included :)
September 29, 2008 2:04
JQuery is great stuff, and this is good news for ASP.Net in general.

I've been using JQuery in my .Net sites for a while (eg - I Want That Flight! ) and showing ways to use it on my blog (eg - Extending .Net with JQuery). So when is MVC going to be 'officially' released?
September 29, 2008 2:09
This is awesome news! Can't wait to read up more on this.
September 29, 2008 3:28
Very cool - I've done some jQuery and ASP.NET MVC work and they work really well together. One thing that I'd really like to see ASP.NET MVC strive for is unobtrusive javascript and really push developers to have a clean separation of presentation (css), document (html) and behavior (js). A lot of web developers understand the need for separation of layers on the server, but most that I meet don't bother once the bits have been pushed down to the client.
September 29, 2008 3:32
Very cool - I've done some jQuery and ASP.NET MVC work and they fit together nicely. One thing that I'd really like to see ASP.NET MVC strive for is unobtrusive javascript and really push developers to have a clean separation of presentation (css), document (html) and behavior (js). A lot of web developers understand the need for separation of layers on the server, but most that I meet don't bother once the bits have been pushed down to the client.
September 29, 2008 3:34
One other thing - is your blog browser sniffing on the server side? I couldn't get my comment to post with Chrome.
September 29, 2008 3:52
Fantastic news... I have been using jquery with my mvc projects and blogged about it several times. I also had to choose a library for my upcoming mvc book and decided on jquery. So it's great to have my decision validated....
September 29, 2008 3:53
Awesome news.
Now it would be really cool if you could do a podcast with Nikhil about Script# and someone at MS got to write a Script# binding for jQuery so you can write those queries in C#... :))
September 29, 2008 4:05
September 29, 2008 4:06
This is great news! Some of the best I've heard in months, as far as ASP.NET goes. Kudos to everyone at Microsoft who was part of making this happen.

For those who are new to using ASP.NET and jQuery together, I have a series of articles about using jQuery with ASP.NET AJAX, which might be handy.
September 29, 2008 4:08
I posted this on the Gu's blog, but I am re-commenting here to take advantage of the HTML comments. Paul Batum is correct that this is a significant change for Microsoft. Here's an exchange I had with Bertrand LeRoy in January 2006 on basing ASP.NET Ajax upon Prototype, the jQuery of its day:


PW: "There's a compelling business case to recreate the wheel when you're dealing with licensed, compiled code. But with a JavaScript framework, your entire source is exposed. Just seems like the perfect opportunity to "stand on the shoulders of giants" instead of writing a bunch of plumbing for extending Object and Array"
BLR: "So even if it was possible for us to stand on top of things like Prototype, it would probably not fit our needs. While it may seem a little silly to say that we can't look at the source code whereas it's plain text that's downloaded by the browser, it doesn't matter from a legal standpoint. We just can't look at it, let alone use it. No more than we can use Reflector on third party .NET libraries to look at their source code. The technical aspect of it does not matter."


I followed up with Bertrand at that year's Mix, and he confirmed that Microsoft was adamant that nobody on the Atlas team could look at other JS frameworks.

Fast-forward 30 months and Microsoft is doing precisely what their legal team would not let them do previously. Prototype and jQuery are both based on the MIT license, so legally they are identical. What precipitated the change in corporate policy?
September 29, 2008 6:20
I am looking forward to the patch of Visual Studio. I very like jQuery.
September 29, 2008 6:30
Kudo Scott, Kudos!

This is GREAT news. jQuery is a GREAT library that makes client-side coding approachable and it's damn good to see that you are not reinventing the wheel here. BRAVO!

This also gives jQuery even more legitimacy and could even lead to jQuery optimizations moved into the browser.

What a happy day!
September 29, 2008 9:01
This is what all the developers are looking at eagerly,finally hands shaken took place among master.
September 29, 2008 9:10
Awesome news, but I have seen a common question asked over at ScottGu's blog and was curious if someone could give a firm answer on it. There is some areas of overlap between jquery and the existing ASP.NET AJAX Script library, such as how AJAX calls are made. Will the MS AJAX Client Library be refactored to use the JQuery library? Another example would be the managing of CSS class names on a dom element, would those be refactored as well? I think if this refactoring were to occur, it would show just how committed MS would be to using JQuery.
September 29, 2008 10:06
It's very cool and good work for ASP.NET Developers. I gave to support for jQuery intellisense 1.2.6 in my blog and I have published jQuery intellisense for version 1.2.6 three months ago. From now on We will take the support from Microsoft for jQuery. So MVC and jQuery will together grow up.
September 29, 2008 10:41
Great news!
September 29, 2008 11:23
Great news!

Btw, you can use hover as a shortcut for mouseover/mouseout.
September 29, 2008 11:27
This is amazing!
September 29, 2008 11:57
Ha,
my asp.net buddies always called me a jquery-whore, now i can laugh at them, i was right in chosing jquery over the ms-ajax framework :D
September 29, 2008 13:12
This is the best news I've seen in a long long time. JQuery is probably the best "extended core" javascript library out there, and I'm really looking forward to see it integrated in VS.

The only thing that makes me sad is seeing this...

$("ul li:even").css("background-color", "lightyellow");

$("ul li").css("width", "450px").css("font-size", "12px");

...such definitions would never be in Javascript code, if only all browsers properly supported CSS. Sigh...

September 29, 2008 13:46
Great news, but what about JQuery UI? Is that officially a separate library, so it won't be included, or do you see it as part of JQuery and you will be including it?

JQuery UI is still fairly immature, but already overlaps quite a bit with some ASP.NET AJAX UI widgets, and will do so more and more as it develops. What plans does MS have, if any, for JQuery UI?
September 29, 2008 17:31
Really enjoyed your podcast on JQuery with John Resig.
September 29, 2008 18:27
seriously, love the direction here.

jquery, templates, ms security, love it!

Is there a way to include built-in support of concatenating all scripts into one larger mother-script to reduce the # of script downloads?
sam
September 29, 2008 18:33
Glad to see it's officially in Visual Studio at last. Do the function call summaries come from the none packed version of JQuery?

I wrote a@http://www.sloppycode.net/articles/using-jquery-with-aspnet-web-services.aspx@this article documenting my adventures using JQuery/AJAX with ASP.NET for dynamic loading which some might find useful. I actually prefer to the atlas/asp.net ajax library.
September 29, 2008 18:36
Would help if I RTM! This article is what I meant to produce.
September 29, 2008 19:24
Scott, nice post. I think in the article your reference to the "ASP.NET AJAX 4.0 Client Template stuff from BLR" is pointing to the ADO.NET Data Services Client Library by mistake. Should it be pointing to http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16766 instead?
September 29, 2008 20:54
Please tell me there's a direction to have more js frameworks in there? Not everyone uses jQuery. As an avid Prototype user I would love to see that integrated.

Scott
September 29, 2008 21:37
Sam - Yes, Script Combining was included with ASP.NET 3.5 SP1: http://www.asp.net/Learn/3.5-SP1/video-296.aspx

GeorgeK - Thanks! Fixed.

Scott Muc - You can certainly use Prototype if it makes you happy, but AFAIK there are no plans to add more.
September 30, 2008 2:30
Awesome news !!!
When you were doing episodes on Javascript week after week, I had guessed something is in the works. Well. There you go. JQuery rocks !
September 30, 2008 3:02
I'm not sure I made myself clear in my typing frenzy. Where does the the intellisense for the function arguments come from? .e.g "1. an expression to search with"?
September 30, 2008 5:35
Is there a chance that Microsoft can host all javascript libraries needed by asp.net / asp.net mvc much in the same way yahoo and google hosts open source resources?
October 07, 2008 3:11
Scott,

Some websites work hard to keep people from scraping data from their website. Perhaps we don't want a competitor to easily get a complete inventory of all of our products and stock levels, which may be data that we want to show to customers on the product page, one product at a time.

ADO.NET Data Services seems to give anyone a direct connection to any data that I need to use in my Javascript. Is there some functionality that would keep people from easily retrieving all of my data from the ADO.NET Data Services REST endpoints?
October 07, 2008 4:09
Josh - That data service doesn't need to be located in the DMZ. It can (if you like) certainly be behind the first firewall. Also, you can use any authorization scheme you like!
October 07, 2008 4:27
Scott - True, but if you want your Javascript on the client's computer to be able to query data from your data service it has to be available directly to the browser. If you proxy the data access, which resides behind your firewall, through some other mechanism -- say a webservice that will only return one product at a time by product_id -- located in the DMZ, what benefits does ADO.NET Data Services provide over just having that proxy access SQL Server directly?
October 09, 2008 13:17
Very nice example :). Any chance we can get a few more, that combine Linq, MVC and ajax/jquery. Still a bit complicated to combine all this new stuff together.
October 14, 2008 13:54
Wondered if you have any concrete plans for when jQuery Intellisense will be available?
October 23, 2008 14:51
That is the great news for me and thanks for the news.
October 25, 2008 1:28
jQuery Intellisense is available in the Beta Version ASP.Net MVC
November 04, 2008 15:09
Nice post...
Rem

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.