jQuery to ship with ASP.NET MVC and Visual Studio
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
- ScottGu on the jQuery/Microsoft goodness
- John Resig on the jQuery/Microsoft announcement
- Bertrand Le Roy on jQuery shipping with VS
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.
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:
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.
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
- JavaScript gets Faster: Brendan Eich, CTO of Mozilla Corporation and Creator of JavaScript
- Hanselminutes Podcasts 128 and 129 - Ajax with Scott Cate and JavaScript with Bertrand Le Roy
- Hanselminutes Podcast 126 - Chat with John Resig, Creator of jQuery
* 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.
About Newsletter
Very happy to see it shipped by MS.
@Scott, when are you doing a podcast with Douglas Crockford?
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?
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.
Will ASP.NET AJAX 4.0 allow that, Scott?
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/
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).
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.
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?
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#... :))
Digg it and let the world know!
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.
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?
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!
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
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...
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?
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?
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.
Scott
GeorgeK - Thanks! Fixed.
Scott Muc - You can certainly use Prototype if it makes you happy, but AFAIK there are no plans to add more.
When you were doing episodes on Javascript week after week, I had guessed something is in the works. Well. There you go. JQuery rocks !
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?
Comments are closed.
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!