In the first installment of this two-part series we explored how you can consume JSONP data sources using hardly any code thanks to the ASP.NET Ajax Library and the powerful networking stack that lies within. This time around we’ll take a look at doing something useful with the data and render it using client templates, again, using the ASP.NET Ajax Library.
In the next few paragraphs, this is what we will build:
At this stage we have received data from the Twitter endpoint and now we want to do something useful with the JSON. As a reminder, here is the code required to get to this point:
- <script src="http://ajax.microsoft.com/ajax/beta/0911/start.debug.js" type="text/javascript"></script>
-
- <script type="text/javascript">
-
- Sys.require([Sys.scripts.WebServices], function callback() {
- Sys.Net.WebServiceProxy.invoke(
- "http://search.twitter.com/search.json?q=jsenior",
- null,
- true,
- null,
- function (result) { alert(result.results[0].text) });
- });
-
- // Workaround for a bug in ASP.NET Ajax Beta, you don't need this in the final version
- function createElement(tag) { return document.createElement(tag); }
-
- </script>
Let’s first construct how our template will look. I want to display some basic information from a twitter search, like twitter handle, the contents of the tweet, when it was posted, and links to Twitter.com so the user can see the original tweet and the profile of the user. Here’s what that looks like based on the documentation provided by Twitter on how their API returns data.
- <div id="TweetList">
- <ul id="resultsView" class="sys-template">
- <li>
- <a sys:href="{{ 'http://twitter.com/' + from_user }}">
- <img sys:src="{{ profile_image_url }}" />
- <b>@{{ from_user }}</b></a>
- says:
- <span class="tweet_created_at">
- (<a sys:href="{{ 'http://twitter.com/' + from_user + '/statuses/' + id }}">
- {{ new Date(created_at).format('dd MMMM yyyy HH:mm:ss') }}</a>)
- </span>
- <br />
- {{ text }}
- <br />
- </li>
- </ul>
- </div>
As you can see, the template is fairly straightforward and the HTML is quite clean. If you run the code in it’s current form you get the template output to the browser including all the curly braces. This is to be expected because we haven’t attached the DataView control to the tempate – that’s the next step.
First we use the Script Loader to bring in the things like DataView, WebServices, Globalization (for the date formatting), and Watermark that we need for this app. We’ll use the Watermark later on when we add an input box for specifying a search query. Remember that the Script Loader takes care of loading all these components so you don’t need to know their dependencies – which is very handy with complex scripts.
- Sys.require([Sys.components.dataView, Sys.scripts.WebServices, Sys.scripts.Globalization, Sys.components.watermark], function () {
-
- var myDV = Sys.create.dataView("#resultsView");
Now that we have told the Script Loader to bring in the DataView control, we can assign it to our template, thus:
- var myDV = Sys.create.dataView("#resultsView");
Notice how we use the Sys namespace to do this (Sys is the ASP.NET Ajax Library namespace) and select the div using its ID, “resultsView”. We are effectively telling the library that we want whatever is in the div to be data aware so when we bind the DataView it will repeat its contents for each row of JSON data – in this example we are repeating the LI element.
At this point let’s stop and add an input box and button to our page so we can specify the query to make to Twitter’s search API. Use this code just before your template DIV.
- <div id="queryarea">
- <input id="query" />
- <button id="btnQuery">Submit</button>
- </div>
- <div id="TweetList">
- <ul id="resultsView" class="sys-template">
- <li>
Nice and easy, huh? Throughout the rest of the sample we are going to refer to the input, “query”, exactly twice, so for performance reasons I am going to select it once and then store that reference in a var so I don’t need to select it any more than is absolutely necessary (this takes extra cycles for libraries like ASP.NET Ajax Library and jQuery). Here’s the code you need to add under your existing JavaScript.
- var queryBox = Sys.get("#query");
Remember, when we brought in the Watermark control (part of the 35 free client-side controls in ASP.NET Ajax Library)? We’re ready to use it! We are going to apply the Watermark control to the input box using the var we have created above. Here we go:
Sys.create.watermark(queryBox, "Search Twitter...", "watermark");
The first two parameters for the above method are fairly straightforward and the third one applies a style to the input box and its watermark so you can make it look how you want.
So now we have that sorted, it’s time to wire up our button to do the search when the user clicks the button. We use the addHandler method for this purpose:
- Sys.addHandler("#btnQuery", "click", function () {
-
- Sys.Net.WebServiceProxy.invoke("http://search.twitter.com/search.json?q=" + (encodeURIComponent(queryBox.value)), null, true, null, function (result) {
- myDV.set_data(result.results);
- });
-
- });
This method’s first parameter takes the selection of an element, in this case “btnQuery” and then applies an HTML event, “click” to it. It then has a callback function that will fire when the user clicks the button; here we are just using an anonymous function which should be familiar to you. Yes, it’s the WebServiceProxy.invoke method, which calls the Twitter Search API and passes it the search string. We pass the results of the query into the function and then bind the dataset to the DataView using myDV.set_data.
Twitter nests its search results in a JSON array so that’s why we must use result.results to get to the data.
We are pretty much set. If we run the code then we’ll have the ability to search twitter and have the results displayed in the template we’ve setup. However, those among you who have been paying attention will notice that we still have our ugly templates displayed with all the curly braces etc prior to searching. Let’s apply a style to hide that and and the same time make our UI a bit more appealing – right now it looks like a dog’s dinner (Englishism for looking a “mess”).
Adding our styles to the page with all the JavaScript code we get the following. The key part for hiding the template is .sys-template. Below is the full HTML page and you can just copy and paste this and you will be good to go.
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head>
- <title>Untitled Page</title>
- <style type="text/css">
-
- .sys-template {
- display: none;
- }
-
- #queryarea
- {
- width: 500px;
- border: 3px solid #1958b7;
- padding: 10px;
- }
-
- input {
- height: 30px;
- width: 280px;
- font-size: 14pt;
- border: 2px dotted #2586d7;
- padding: 5px;
- }
-
- button
- {
- height: 45px;
- width: 110px;
- border: 2px solid #1958b7;
- background-color: #FFFFFF;
- font-size: 14pt;
- color: #1958b7;
- }
-
- .watermark
- {
- font-style: italic;
- color: Gray;
- }
-
-
- .tweet_created_at {
- font-size: 8pt;
- text-align: right;
- }
-
- img {
- height: 50px;
- width: 50px;
- float: left;
- padding: 5px;
- margin: 5px;
- vertical-align: top;
- margin-bottom: 15px;
- border: 2px solid white;
- }
-
- #TweetList {
- width: 490px;
- padding: 0 0 1em 0;
- margin-bottom: 1em;
- font-family: 'Trebuchet MS', 'Lucida Grande',
- Verdana, Lucida, Geneva, Helvetica,
- Arial, sans-serif;
- font-size: 10pt;
- color: #333;
- }
-
- #TweetList ul {
- list-style: none;
- margin: 0;
- padding: 0;
- border: none;
- }
-
- #TweetList li {
- border-bottom: 1px solid #90bade;
- margin: 0;
- display: block;
- padding: 5px 0px 5px 0.5em;
- border-left: 10px solid #1958b7;
- border-right: 10px solid #508fc4;
- background-color: #2175bc;
- color: #fff;
- text-decoration: none;
- width: 100%;
-
- height: 85px;
- }
-
- html>body #TweetList li a {
- width: auto;
- color: White;
- }
-
- #TweetList li a:hover {
- color: Blue;
- }
-
-
- </style>
-
- <!-- Get the script loader from the CDN -->
- <script src="http://ajax.microsoft.com/ajax/beta/0911/start.debug.js" type="text/javascript"></script>
- <script src="http://ajax.microsoft.com/ajax/beta/0911/Extended/ExtendedControls.debug.js" type="text/javascript"></script>
-
- <script type="text/javascript">
-
- // We need dataView for templating, Web Services for JSONP call, Globalization for formatting the date, watermark for the input box
- Sys.require([Sys.components.dataView, Sys.scripts.WebServices, Sys.scripts.Globalization, Sys.components.watermark], function () {
-
- var myDV = Sys.create.dataView("#resultsView");
- var queryBox = Sys.get("#query");
-
-
- Sys.create.watermark(queryBox, "Search Twitter...", "watermark");
-
-
- Sys.addHandler("#btnQuery", "click", function () {
-
- Sys.Net.WebServiceProxy.invoke("http://search.twitter.com/search.json?q=" + (encodeURIComponent(queryBox.value)), null, true, null, function (result) {
- myDV.set_data(result.results);
- });
-
- });
-
- });
-
- </script>
-
- <script type="text/javascript">
-
- // Workaround for a bug in ASP.NET Ajax Beta, you don't need this in the final version
- function createElement(tag) { return document.createElement(tag); }
-
- </script>
-
- </head>
- <body>
- <div id="queryarea">
- <input id="query" />
- <button id="btnQuery">Submit</button>
- </div>
- <div id="TweetList">
- <ul id="resultsView" class="sys-template">
- <li>
- <a sys:href="{{ 'http://twitter.com/' + from_user }}">
- <img sys:src="{{ profile_image_url }}" />
- <b>@{{ from_user }}</b></a>
- says:
- <span class="tweet_created_at">
- (<a sys:href="{{ 'http://twitter.com/' + from_user + '/statuses/' + id }}">
- {{ new Date(created_at).format('dd MMMM yyyy HH:mm:ss') }}</a>)
- </span>
- <br />
- {{ text }}
- <br />
- </li>
- </ul>
- </div>
- </body>
- </html>
This brings to close this 2-part series showing how to create a Twitter search in pure client-side code thanks to the ASP.NET Ajax Library. We’ve covered the following important topics:
- Getting the library from the Microsoft Ajax CDN
- Using the Script Loader to load and execute all the required scripts and components
- Applying the DataView Control to the Page
- Creating a watermark
- Adding an onClick handler to the button
- Calling the Twitter Search API using JSONP
- Setting up our client template