<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2titles.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemtitles.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Stephen Walther</title>
	
	<link>http://stephenwalther.com/blog</link>
	<description>ASP.NET MVC, Windows Metro, JavaScript</description>
	<lastBuildDate>Fri, 25 May 2012 00:34:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/StephenWalther" /><feedburner:info uri="stephenwalther" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/StephenWalther" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://www.addtoany.com/?linkname=Stephen%20Walther&amp;linkurl=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther&amp;type=feed" src="http://www.addtoany.com/addfr-b.gif">Add to Any Feed Reader</feedburner:feedFlare><feedburner:browserFriendly>Get the latest news, tips, and articles on ASP.NET MVC by subscribing to Stephen Walther's blog.</feedburner:browserFriendly><item>
		<title>Metro Walkthrough: Creating a Task List with a ListView and IndexedDB</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/aQRMWWofeOA/metro-walkthrough-creating-a-task-list-with-a-listview-and-indexeddb.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/24/metro-walkthrough-creating-a-task-list-with-a-listview-and-indexeddb.aspx#comments</comments>
		<pubDate>Fri, 25 May 2012 00:34:48 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=544</guid>
		<description><![CDATA[The goal of this blog entry is to describe how you can work with data in a Metro style application written with JavaScript. In particular, we create a super simple Task List application which enables you to create and delete tasks. Here’s a video which demonstrates how the Task List application works: In order to [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog entry is to describe how you can work with data in a Metro style application written with JavaScript. In particular, we create a super simple Task List application which enables you to create and delete tasks.
<p>Here’s a video which demonstrates how the Task List application works:
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image001.gif"><img style="display: inline" title="clip_image001" alt="clip_image001" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image001_thumb.gif" width="592" height="320"></a>
<p>In order to build this application, I had to take advantage of several features of the WinJS library and technologies including:
<ul>
<li>IndexedDB – The Task List application stores data in an IndexedDB database. <br /> 
<li>HTML5 Form Validation – The Task List application uses HTML5 validation to ensure that a required field has a value. <br /> 
<li>ListView Control – The Task List application displays the tasks retrieved from the IndexedDB database in a WinJS ListView control. </li>
</ul>
<h3>Creating the IndexedDB Database</h3>
<p>The Task List application stores all of its data in an IndexedDB database named TasksDB. This database is opened/created with the following code:
<pre class="brush: js;">var db;
var req = window.msIndexedDB.open("TasksDB", 1);
req.onerror = function () {
    console.log("Could not open database");
};
req.onupgradeneeded = function (evt) {
    var newDB = evt.target.result;
    newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true });
};
</pre>
<p>The msIndexedDB.open() method accepts two parameters: the name of the database to open and the version of the database to open. If a database with a matching version already exists, then calling the msIndexedDB.open() method opens a connection to the existing database. If the database does not exist then the upgradeneeded event is raised. </p>
<p>You handle the upgradeneeded event to create a new database. In the code above, the upgradeneeded event handler creates an object store named “tasks” (An object store roughly corresponds to a database table). When you add items to the tasks object store then each item gets an id property with an auto-incremented value automatically. </p>
<p>The code above also includes an error event handler. If the IndexedDB database cannot be opened or created, for whatever reason, then an error message is written to the Visual Studio JavaScript Console window. </p>
<h3>Displaying a List of Tasks</h3>
<p>The TaskList application retrieves its list of tasks from the tasks object store, which we created above, and displays the list of tasks in a ListView control. Here is how the ListView control is declared:
<pre class="brush: xml;">&lt;div id="tasksListView"
    data-win-control="WinJS.UI.ListView"
    data-win-options="{
        itemDataSource: TaskList.tasks.dataSource,
        itemTemplate: select('#taskTemplate'),
        tapBehavior: 'toggleSelect',
        selectionMode: 'multi',
        layout: { type: WinJS.UI.ListLayout }
    }"&gt;
&lt;/div&gt;
</pre>
<p>The ListView control is bound to the TaskList.tasks.dataSource data source. The TaskList.tasks.dataSource is created with the following code:
<pre class="brush: js;">// Create the data source
var tasks = new WinJS.Binding.List();

// Open the database
var db;
var req = window.msIndexedDB.open("TasksDB", 1);
req.onerror = function () {
    console.log("Could not open database");
};
req.onupgradeneeded = function (evt) {
    var newDB = evt.target.result;
    newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true });
};

// Load the data source with data from the database
req.onsuccess = function () {
    db = req.result;
    var tran = db.transaction("tasks");
    tran.objectStore("tasks").openCursor().onsuccess = function(event) {
        var cursor = event.target.result;
        tasks.dataSource.beginEdits();
        if (cursor) {
            tasks.dataSource.insertAtEnd(null, cursor.value);
            cursor.continue();
        } else {
            tasks.dataSource.endEdits();
        };
    };  

};

// Expose the data source and functions
WinJS.Namespace.define("TaskList", {
    tasks: tasks
});
</pre>
<p>Notice the success event handler. This handler is called when a database is successfully opened/created. In the code above, all of the items from the tasks object store are retrieved into a cursor and added to a WinJS.Binding.List object named tasks. </p>
<p>Because the ListView control is bound to the WinJS.Binding.List object, copying the tasks from the object store into the WinJS.Binding.List object causes the tasks to appear in the ListView: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002_thumb.png" width="481" height="323"></a> </p>
<h3>Adding a New Task</h3>
<p>You add a new task in the Task List application by entering the title of a new task into an HTML form and clicking the Add button. Here’s the markup for creating the form:
<pre class="brush: xml;">&lt;form id="addTaskForm"&gt;
    &lt;input id="newTaskTitle" title="New Task" required /&gt;
    &lt;button&gt;Add&lt;/button&gt;
&lt;/form&gt;
</pre>
<p>Notice that the INPUT element includes a <i>required</i> attribute. In a Metro application, you can take advantage of HTML5 Validation to validate form fields. If you don’t enter a value for the newTaskTitle field then the following validation error message is displayed: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image0031.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image003" border="0" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003_thumb1.png" width="385" height="256"></a> </p>
<p>For a brief introduction to HTML5 validation, see my previous blog entry: </p>
<blockquote>
<p><a href="http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx">http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx</a> </p>
</blockquote>
<p>When you click the Add button, the form is submitted and the form submit event is raised. The following code is executed in the default.js file:
<pre class="brush: js;">// Handle Add Task
document.getElementById("addTaskForm").addEventListener("submit", function (evt) {
    evt.preventDefault();
    var newTaskTitle = document.getElementById("newTaskTitle");
    TaskList.addTask({ title: newTaskTitle.value });
    newTaskTitle.value = "";
});
</pre>
<p>The code above retrieves the title of the new task and calls the addTask() method in the tasks.js file. Here’s the code for the addTask() method which is responsible for actually adding the new task to the IndexedDB database:
<pre class="brush: js;">// Add a new task
function addTask(taskToAdd) {
    var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE);
    var addRequest = transaction.objectStore("tasks").add(taskToAdd);
    addRequest.onsuccess = function (evt) {
        taskToAdd.id = evt.target.result;
        tasks.dataSource.insertAtEnd(null, taskToAdd);
    }
}
</pre>
<p>The code above does two things. First, it adds the new task to the tasks object store in the IndexedDB database. Second, it adds the new task to the data source bound to the ListView. The dataSource.insertAtEnd() method is called to add the new task to the data source so the new task will appear in the ListView (with a nice little animation). </p>
<h3>Deleting Existing Tasks</h3>
<p>The Task List application enables you to select one or more tasks by clicking or tapping on one or more tasks in the ListView. When you click the Delete button, the selected tasks are removed from both the IndexedDB database and the ListView. </p>
<p>For example, in the following screenshot, two tasks are selected. The selected tasks appear with a teal background and a checkmark: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image004.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image004_thumb.png" width="614" height="293"></a> </p>
<p>When you click the Delete button, the following code in the default.js file is executed:
<pre class="brush: js;">// Handle Delete Tasks
document.getElementById("btnDeleteTasks").addEventListener("click", function (evt) {
    tasksListView.winControl.selection.getItems().then(function(items) {
        items.forEach(function (item) {
            TaskList.deleteTask(item);
        });
    });
});
</pre>
<p>The selected tasks are retrieved with the TaskList selection.getItem() method. In the code above, the deleteTask() method is called for each of the selected tasks. </p>
<p>Here’s the code for the deleteTask() method:
<pre class="brush: js;">// Delete an existing task
function deleteTask(listViewItem) {
    // Database key != ListView key
    var dbKey = listViewItem.data.id;
    var listViewKey = listViewItem.key;

    // Remove item from db and, if success, remove item from ListView
    var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE);
    var deleteRequest = transaction.objectStore("tasks").delete(dbKey);
    deleteRequest.onsuccess = function () {
        tasks.dataSource.remove(listViewKey);
    }
}
</pre>
<p>This code does two things: it deletes the existing task from the database and removes the existing task from the ListView. In both cases, the right task is removed by using the key associated with the task. However, the task key is different in the case of the database and in the case of the ListView. </p>
<p>In the case of the database, the task key is the value of the task id property. In the case of the ListView, on the other hand, the task key is auto-generated by the ListView. </p>
<p>When the task is removed from the ListView, an animation is used to collapse the tasks which appear above and below the task which was removed. </p>
<h3>The Complete Code</h3>
<p>Above, I did a lot of jumping around between different files in the application and I left out sections of code. For the sake of completeness, I want to include the entire code here: the default.html, default.js, and tasks.js files. </p>
<p>Here are the contents of the default.html file. This file contains the UI for the Task List application:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Task List&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- TaskList references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="js/tasks.js"&gt;&lt;/script&gt;

    &lt;style type="text/css"&gt;
        body {
            font-size: x-large;
        }

        form {
            display:  inline;
        }

        #appContainer {
            margin:  20px;
            width:  600px;
        }

        .win-container {
            padding:  10px;
        }

    &lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div&gt;

        &lt;!-- Templates --&gt;
        &lt;div id="taskTemplate"
            data-win-control="WinJS.Binding.Template"&gt;
            &lt;div&gt;
                &lt;span data-win-bind="innerText:title"&gt;&lt;/span&gt;
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;h1&gt;Super Task List&lt;/h1&gt;

        &lt;div id="appContainer"&gt;
            &lt;form id="addTaskForm"&gt;
                &lt;input id="newTaskTitle" title="New Task" required /&gt;
                &lt;button&gt;Add&lt;/button&gt;
            &lt;/form&gt;
            &lt;button id="btnDeleteTasks"&gt;Delete&lt;/button&gt;

            &lt;div id="tasksListView"
                data-win-control="WinJS.UI.ListView"
                data-win-options="{
                    itemDataSource: TaskList.tasks.dataSource,
                    itemTemplate: select('#taskTemplate'),
                    tapBehavior: 'toggleSelect',
                    selectionMode: 'multi',
                    layout: { type: WinJS.UI.ListLayout }
                }"&gt;
            &lt;/div&gt;
        &lt;/div&gt;

    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Here is the code for the default.js file. This code wires up the Add Task form and Delete button:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            WinJS.UI.processAll().then(function () {

                // Get reference to Tasks ListView
                var tasksListView = document.getElementById("tasksListView");

                // Handle Add Task
                document.getElementById("addTaskForm").addEventListener("submit", function (evt) {
                    evt.preventDefault();
                    var newTaskTitle = document.getElementById("newTaskTitle");
                    TaskList.addTask({ title: newTaskTitle.value });
                    newTaskTitle.value = "";
                });

                // Handle Delete Tasks
                document.getElementById("btnDeleteTasks").addEventListener("click", function (evt) {
                    tasksListView.winControl.selection.getItems().then(function(items) {
                        items.forEach(function (item) {
                            TaskList.deleteTask(item);
                        });
                    });

                });

            });
        }
    };

    app.start();
})();
</pre>
<p>Finally, here is the tasks.js file. This file contains all of the code for opening, creating, and interacting with IndexedDB:
<pre class="brush: js;">(function () {
    "use strict";

    // Create the data source
    var tasks = new WinJS.Binding.List();

    // Open the database
    var db;
    var req = window.msIndexedDB.open("TasksDB", 1);
    req.onerror = function () {
        console.log("Could not open database");
    };
    req.onupgradeneeded = function (evt) {
        var newDB = evt.target.result;
        newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true });
    };

    // Load the data source with data from the database
    req.onsuccess = function () {
        db = req.result;
        var tran = db.transaction("tasks");
        tran.objectStore("tasks").openCursor().onsuccess = function(event) {
            var cursor = event.target.result;
            tasks.dataSource.beginEdits();
            if (cursor) {
                tasks.dataSource.insertAtEnd(null, cursor.value);
                cursor.continue();
            } else {
                tasks.dataSource.endEdits();
            };
        };  

    };

    // Add a new task
    function addTask(taskToAdd) {
        var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE);
        var addRequest = transaction.objectStore("tasks").add(taskToAdd);
        addRequest.onsuccess = function (evt) {
            taskToAdd.id = evt.target.result;
            tasks.dataSource.insertAtEnd(null, taskToAdd);
        }
    }

    // Delete an existing task
    function deleteTask(listViewItem) {
        // Database key != ListView key
        var dbKey = listViewItem.data.id;
        var listViewKey = listViewItem.key;

        // Remove item from db and, if success, remove item from ListView
        var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE);
        var deleteRequest = transaction.objectStore("tasks").delete(dbKey);
        deleteRequest.onsuccess = function () {
            tasks.dataSource.remove(listViewKey);
        }
    }

    // Expose the data source and functions
    WinJS.Namespace.define("TaskList", {
        tasks: tasks,
        addTask: addTask,
        deleteTask: deleteTask
    });

})();
</pre>
<h3>Summary</h3>
<p>I wrote this blog entry because I wanted to create a walkthrough of building a simple database-driven application. In particular, I wanted to demonstrate how you can use a ListView control with an IndexedDB database to store and retrieve database data. </p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=aQRMWWofeOA:H910Q8HGPeg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/aQRMWWofeOA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/24/metro-walkthrough-creating-a-task-list-with-a-listview-and-indexeddb.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/24/metro-walkthrough-creating-a-task-list-with-a-listview-and-indexeddb.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Dynamically Switching Templates with a WinJS ListView</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/1NWSxk--0Ts/metro-dynamically-switching-templates-with-a-winjs-listview.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/23/metro-dynamically-switching-templates-with-a-winjs-listview.aspx#comments</comments>
		<pubDate>Wed, 23 May 2012 16:15:59 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=534</guid>
		<description><![CDATA[Imagine that you want to display a list of products using the WinJS ListView control. Imagine, furthermore, that you want to use different templates to display different products. In particular, when a product is on sale, you want to display the product using a special “On Sale” template. In this blog entry, I explain how [...]]]></description>
			<content:encoded><![CDATA[<p>Imagine that you want to display a list of products using the WinJS ListView control. Imagine, furthermore, that you want to use different templates to display different products. In particular, when a product is on sale, you want to display the product using a special “On Sale” template.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image0022.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002_thumb2.jpg" width="628" height="295"></a>
<p>In this blog entry, I explain how you can switch templates dynamically when displaying items with a ListView control. In other words, you learn how to use more than one template when displaying items with a ListView control.<br />
<h3>Creating the Data Source</h3>
<p>Let’s start by creating the data source for the ListView. Nothing special here – our data source is a list of products. Two of the products, Oranges and Apples, are on sale.
<pre class="brush: js;">(function () {
    "use strict";

    var products = new WinJS.Binding.List([
            { name: "Milk", price: 2.44 },
            { name: "Oranges", price: 1.99, onSale: true },
            { name: "Wine", price: 8.55 },
            { name: "Apples", price: 2.44, onSale: true },
            { name: "Steak", price: 1.99 },
            { name: "Eggs", price: 2.44 },
            { name: "Mushrooms", price: 1.99 },
            { name: "Yogurt", price: 2.44 },
            { name: "Soup", price: 1.99 },
            { name: "Cereal", price: 2.44 },
            { name: "Pepsi", price: 1.99 }
    ]);

    WinJS.Namespace.define("ListViewDemos", {
        products: products
    });

})();
</pre>
<p>The file above is saved with the name products.js and referenced by the default.html page described below. </p>
<h3>Declaring the Templates and ListView Control</h3>
<p>Next, we need to declare the ListView control and the two Template controls which we will use to display template items. The markup below appears in the default.html file:
<pre class="brush: xml;">&lt;!-- Templates --&gt;
&lt;div id="productItemTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="product"&gt;
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;div id="productOnSaleTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="product onSale"&gt;
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        (On Sale!)
    &lt;/div&gt;
&lt;/div&gt;

&lt;!-- ListView --&gt;
&lt;div id="productsListView"
    data-win-control="WinJS.UI.ListView"
    data-win-options="{
            itemDataSource: ListViewDemos.products.dataSource,
            layout: { type: WinJS.UI.ListLayout }

        }"&gt;
&lt;/div&gt;
</pre>
<p>In the markup above, two Template controls are declared. The first template is used when rendering a normal product and the second template is used when rendering a product which is on sale. The second template, unlike the first template, includes the text “(On Sale!)”. </p>
<p>The ListView control is bound to the data source which we created in the previous section. The ListView itemDataSource property is set to the value ListViewDemos.products.dataSource. Notice that we do not set the ListView itemTemplate property. We set this property in the default.js file. </p>
<h3>Switching Between Templates</h3>
<p>All of the magic happens in the default.js file. The default.js file contains the JavaScript code used to switch templates dynamically. </p>
<p>Here’s the entire contents of the default.js file:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            WinJS.UI.processAll().then(function () {
                var productsListView = document.getElementById("productsListView");
                productsListView.winControl.itemTemplate = itemTemplateFunction;

            });;

        }
    };

    function itemTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {
            // Select either normal product template or on sale template
            var itemTemplate = document.getElementById("productItemTemplate");
            if (item.data.onSale) {
                itemTemplate = document.getElementById("productOnSaleTemplate");
            };

            // Render selected template to DIV container
            var container = document.createElement("div");
            itemTemplate.winControl.render(item.data, container);
            return container;
        });
    }

    app.start();
})();
</pre>
<p>In the code above, a function is assigned to the ListView itemTemplate property with the following line of code:
<pre class="brush: js;">productsListView.winControl.itemTemplate = itemTemplateFunction;
</pre>
<p>&nbsp;
<p>The itemTemplateFunction returns a DOM element which is used for the template item. Depending on the value of the product onSale property, the DOM element is generated from either the productItemTemplate or the productOnSaleTemplate template. </p>
<h3>Using Binding Converters instead of Multiple Templates</h3>
<p>In the previous sections, I explained how you can use different templates to render normal products and on sale products. There is an alternative approach to displaying different markup for normal products and on sale products. Instead of creating two templates, you can create a single template which contains separate DIV elements for a normal product and an on sale product. </p>
<p>The following default.html file contains a single item template and a ListView control bound to the template.
<pre class="brush: xml;">&lt;!-- Template --&gt;
&lt;div id="productItemTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="product" data-win-bind="style.display: onSale ListViewDemos.displayNormalProduct"&gt;
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;

    &lt;div class="product onSale" data-win-bind="style.display: onSale ListViewDemos.displayOnSaleProduct"&gt;
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        (On Sale!)
    &lt;/div&gt;
&lt;/div&gt;

&lt;!-- ListView --&gt;
&lt;div id="productsListView"
    data-win-control="WinJS.UI.ListView"
    data-win-options="{
            itemDataSource: ListViewDemos.products.dataSource,
            itemTemplate: select('#productItemTemplate'),
            layout: { type: WinJS.UI.ListLayout }
        }"&gt;
&lt;/div&gt;
</pre>
<p>The first DIV element is used to render a normal product:
<pre class="brush: xml;">&lt;div class="product" data-win-bind="style.display: onSale ListViewDemos.displayNormalProduct"&gt;
    &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
    &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
&lt;/div&gt;
</pre>
<p>The second DIV element is used to render an “on sale” product:
<pre class="brush: xml;">&lt;div class="product onSale" data-win-bind="style.display: onSale ListViewDemos.displayOnSaleProduct"&gt;
    &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
    &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    (On Sale!)
&lt;/div&gt;
</pre>
<p>Notice that both templates include a data-win-bind attribute. These data-win-bind attributes are used to show the “normal” template when a product is not on sale and show the “on sale” template when a product is on sale. These attributes set the Cascading Style Sheet display attribute to either “none” or “block”. </p>
<p>The data-win-bind attributes take advantage of binding converters. The binding converters are defined in the default.js file:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            WinJS.UI.processAll();
        }
    };

    WinJS.Namespace.define("ListViewDemos", {
        displayNormalProduct: WinJS.Binding.converter(function (onSale) {
            return onSale ? "none" : "block";
        }),

        displayOnSaleProduct: WinJS.Binding.converter(function (onSale) {
            return onSale ? "block" : "none";
        })

    });

    app.start();
})();
</pre>
<p>The ListViewDemos.displayNormalProduct binding converter converts the value true or false to the value “none” or “block”. The ListViewDemos.displayOnSaleProduct binding converter does the opposite; it converts the value true or false to the value “block” or “none” (Sadly, you cannot simply place a NOT operator before the onSale property in the binding expression – you need to create both converters). </p>
<p>The end result is that you can display different markup depending on the value of the product onSale property. Either the contents of the first or second DIV element are displayed: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image003" border="0" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003_thumb.png" width="403" height="378"></a> </p>
<h3>Summary</h3>
<p>In this blog entry, I’ve explored two approaches to displaying different markup in a ListView depending on the value of a data item property. The bulk of this blog entry was devoted to explaining how you can assign a function to the ListView itemTemplate property which returns different templates. We created both a productItemTemplate and productOnSaleTemplate and displayed both templates with the same ListView control. </p>
<p>We also discussed how you can create a single template and display different markup by using binding converters. The binding converters are used to set a DIV element’s display property to either “none” or “block”. We created a binding converter which displays normal products and a binding converter which displays “on sale” products.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=1NWSxk--0Ts:OQZKC1qKTeM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/1NWSxk--0Ts" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/23/metro-dynamically-switching-templates-with-a-winjs-listview.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/23/metro-dynamically-switching-templates-with-a-winjs-listview.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Creating a Master/Detail View with a WinJS ListView Control</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/9_vtYcceTTU/metro-creating-a-masterdetail-view-with-a-winjs-listview-control.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/21/metro-creating-a-masterdetail-view-with-a-winjs-listview-control.aspx#comments</comments>
		<pubDate>Mon, 21 May 2012 15:12:09 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=528</guid>
		<description><![CDATA[The goal of this blog entry is to explain how you can create a simple master/detail view by using the WinJS ListView and Template controls. In particular, I explain how you can use a ListView control to display a list of movies and how you can use a Template control to display the details of [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog entry is to explain how you can create a simple master/detail view by using the WinJS ListView and Template controls. In particular, I explain how you can use a ListView control to display a list of movies and how you can use a Template control to display the details of the selected movie.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image0021.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002_thumb1.jpg" width="628" height="403"></a>
<p>Creating a master/detail view requires completing the following four steps: </p>
<ol>
<li>Create the data source – The data source contains the list of movies. <br /> 
<li>Declare the ListView control – The ListView control displays the entire list of movies. It is the master part of the master/detail view. <br /> 
<li>Declare the Details Template control – The Details Template control displays the details for the selected movie. It is the details part of the master/detail view. <br /> 
<li>Handle the selectionchanged event – You handle the selectionchanged event to display the details for a movie when a new movie is selected. </li>
</ol>
<h3>Creating the Data Source</h3>
<p>There is nothing special about our data source. We initialize a WinJS.Binding.List object to represent a list of movies:
<pre class="brush: js;">(function () {
    "use strict";

    var movies = new WinJS.Binding.List([
        { title: "Star Wars", director: "Lucas"},
        { title: "Shrek", director: "Adamson" },
        { title: "Star Trek", director: "Abrams" },
        { title: "Spiderman", director: "Raimi" },
        { title: "Memento", director: "Nolan" },
        { title: "Minority Report", director: "Spielberg" }
    ]);

    // Expose the data source
    WinJS.Namespace.define("ListViewDemos", {
        movies: movies
    });

})();
</pre>
<p>The data source is exposed to the rest of our application with the name <em>ListViewDemos.movies</em>. </p>
<h3>Declaring the ListView Control</h3>
<p>The ListView control is declared with the following markup:
<pre class="brush: xml;">&lt;div id="movieList"
    data-win-control="WinJS.UI.ListView"
    data-win-options="{
        itemDataSource: ListViewDemos.movies.dataSource,
        itemTemplate: select('#masterItemTemplate'),
        tapBehavior: 'directSelect',
        selectionMode: 'single',
        layout: { type: WinJS.UI.ListLayout }
    }"&gt;
&lt;/div&gt;
</pre>
<p>The data-win-options attribute is used to set the following properties of the ListView control: </p>
<ul>
<li>itemDataSource – The ListView is bound to the list of movies which we created in the previous section. Notice that the ListView is bound to <em>ListViewDemos.movies.dataSource</em> and not just <em>ListViewDemos.movies</em>. 
<li>itemTemplate – The item template contains the template used for rendering each item in the ListView. The markup for this template is included below. 
<li>tabBehavior – This enumeration determines what happens when you tap or click on an item in the ListView. The possible values are directSelect, toggleSelect, invokeOnly, none. Because we want to handle the selectionchanged event, we set tapBehavior to the value directSelect. 
<li>selectionMode – This enumeration determines whether you can select multiple items or only a single item. The possible values are none, single, multi. In the code above, this property is set to the value single. 
<li>layout – You can use ListLayout or GridLayout with a ListView. If you want to display a vertical ListView, then you should select ListLayout. </li>
</ul>
<p>You must associate a ListView with an item template if you want to render anything interesting. The ListView above is associated with an item template named #masterItemTemplate. Here’s the markup for the masterItemTemplate:
<pre class="brush: xml;">&lt;div id="masterItemTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="movie"&gt;
        &lt;span data-win-bind="innerText:title"&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>This template simply renders the title of each movie. </p>
<h3>Declaring the Details Template Control</h3>
<p>The details part of the master/detail view is created with the help of a Template control. Here’s the markup used to declare the Details Template control:
<pre class="brush: xml;">&lt;div id="detailsTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div&gt;
        &lt;div&gt;
            Title:
            &lt;span data-win-bind="innerText:title"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            Director:
            &lt;span data-win-bind="innerText:director"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>The Details Template control displays the movie title and director.</p>
<p>&nbsp;<a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image3.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image_thumb3.png" width="644" height="413"></a></p>
<h3>Handling the selectionchanged Event</h3>
<p>The ListView control can raise two types of events: the iteminvoked and selectionchanged events. The iteminvoked event is raised when you click on a ListView item. The selectionchanged event is raised when one or more ListView items are selected. </p>
<p>When you set the tapBehavior property of the ListView control to the value “directSelect” then tapping or clicking a list item raised both the iteminvoked and selectionchanged event. Tapping a list item causes the item to be selected and the item appears with a checkmark. </p>
<p>In our code, we handle the selectionchanged event to update the movie details Template when you select a new movie. </p>
<p>Here’s the code from the default.js file used to handle the selectionchanged event:
<pre class="brush: js;">var movieList = document.getElementById("movieList");
var detailsTemplate = document.getElementById("detailsTemplate");
var movieDetails = document.getElementById("movieDetails");

// Setup selectionchanged handler
movieList.winControl.addEventListener("selectionchanged", function (evt) {
    if (movieList.winControl.selection.count() &gt; 0) {
        movieList.winControl.selection.getItems().then(function (items) {
            // Clear the template container
            movieDetails.innerHTML = "";
            // Render the template
            detailsTemplate.winControl.render(items[0].data, movieDetails);
        });
    }
});
</pre>
<p>The code above sets up an event handler (listener) for the selectionchanged event. The event handler first verifies that an item has been selected in the ListView (selection.count() &gt; 0). Next, the details for the movie are rendered using the movie details Template (we created this Template in the previous section). </p>
<h3>The Complete Code</h3>
<p>For the sake of completeness, I’ve included the complete code for the master/detail view below. I’ve included both the default.html, default.js, and movies.js files. </p>
<p>Here is the final code for the default.html file:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;ListViewMasterDetail&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- ListViewMasterDetail references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="js/movies.js"&gt;&lt;/script&gt;

    &lt;style type="text/css"&gt;

        body {
            font-size:  xx-large;
        }

        .movie {
            padding: 5px;
        }

        #masterDetail {
            display: -ms-box;
        }

        #movieList {
            width:  300px;
            margin:  20px;
        }

        #movieDetails {
            margin:  20px;
        }

    &lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;!-- Templates --&gt;
    &lt;div id="masterItemTemplate" data-win-control="WinJS.Binding.Template"&gt;
        &lt;div class="movie"&gt;
            &lt;span data-win-bind="innerText:title"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div id="detailsTemplate" data-win-control="WinJS.Binding.Template"&gt;
        &lt;div&gt;
            &lt;div&gt;
                Title:
                &lt;span data-win-bind="innerText:title"&gt;&lt;/span&gt;
            &lt;/div&gt;
            &lt;div&gt;
                Director:
                &lt;span data-win-bind="innerText:director"&gt;&lt;/span&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Master/Detail --&gt;
    &lt;div id="masterDetail"&gt;
        &lt;!-- Master --&gt;
        &lt;div id="movieList"
            data-win-control="WinJS.UI.ListView"
            data-win-options="{
                itemDataSource: ListViewDemos.movies.dataSource,
                itemTemplate: select('#masterItemTemplate'),
                tapBehavior: 'directSelect',
                selectionMode: 'single',
                layout: { type: WinJS.UI.ListLayout }
            }"&gt;
        &lt;/div&gt;

        &lt;!-- Detail --&gt;
        &lt;div id="movieDetails"&gt;&lt;/div&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Here is the default.js file:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            WinJS.UI.processAll();

            var movieList = document.getElementById("movieList");
            var detailsTemplate = document.getElementById("detailsTemplate");
            var movieDetails = document.getElementById("movieDetails");

            // Setup selectionchanged handler
            movieList.winControl.addEventListener("selectionchanged", function (evt) {
                if (movieList.winControl.selection.count() &gt; 0) {
                    movieList.winControl.selection.getItems().then(function (items) {
                        // Clear the template container
                        movieDetails.innerHTML = "";
                        // Render the template
                        detailsTemplate.winControl.render(items[0].data, movieDetails);
                    });
                }
            });

        }
    };

    app.start();
})();
</pre>
<p>&nbsp;
<p>Here is the movies.js file:
<pre class="brush: js;">(function () {
    "use strict";

    var movies = new WinJS.Binding.List([
        { title: "Star Wars", director: "Lucas"},
        { title: "Shrek", director: "Adamson" },
        { title: "Star Trek", director: "Abrams" },
        { title: "Spiderman", director: "Raimi" },
        { title: "Memento", director: "Nolan" },
        { title: "Minority Report", director: "Spielberg" }
    ]);

    // Expose the data source
    WinJS.Namespace.define("ListViewDemos", {
        movies: movies
    });

})();
</pre>
<p>&nbsp;<br />
<h3>Summary</h3>
<p>The purpose of this blog entry was to describe how to create a simple master/detail view by taking advantage of the WinJS ListView control. We handled the selectionchanged event of the ListView control to display movie details when you select a movie in the ListView.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=9_vtYcceTTU:mpoQOgsJLiM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/9_vtYcceTTU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/21/metro-creating-a-masterdetail-view-with-a-winjs-listview-control.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/21/metro-creating-a-masterdetail-view-with-a-winjs-listview-control.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Grouping Items in a ListView Control</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/_qbAByxPzNI/metro-grouping-items-in-a-listview-control.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/18/metro-grouping-items-in-a-listview-control.aspx#comments</comments>
		<pubDate>Sat, 19 May 2012 00:14:52 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=521</guid>
		<description><![CDATA[The purpose of this blog entry is to explain how you can group list items when displaying the items in a WinJS ListView control. In particular, you learn how to group a list of products by product category. Displaying a grouped list of items in a ListView control requires completing the following steps: Create a [...]]]></description>
			<content:encoded><![CDATA[<p>The purpose of this blog entry is to explain how you can group list items when displaying the items in a WinJS ListView control. In particular, you learn how to group a list of products by product category.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image2.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image_thumb2.png" width="941" height="583"></a>
<p>Displaying a grouped list of items in a ListView control requires completing the following steps:
<ol>
<li>Create a Grouped data source from a List data source
<li>Create a Grouped Header Template
<li>Declare the ListView control so it groups the list items </li>
</ol>
<h4>Creating the Grouped Data Source</h4>
<p>Normally, you bind a ListView control to a WinJS.Binding.List object. If you want to render list items in groups, then you need to bind the ListView to a grouped data source instead.
<p>The following code – contained in a file named products.js &#8212; illustrates how you can create a standard WinJS.Binding.List object from a JavaScript array and then return a grouped data source from the WinJS.Binding.List object by calling its createGrouped() method:
<pre class="brush: js;">(function () {
    "use strict";

    // Create List data source
    var products = new WinJS.Binding.List([
            { name: "Milk", price: 2.44, category: "Beverages" },
            { name: "Oranges", price: 1.99, category: "Fruit" },
            { name: "Wine", price: 8.55, category: "Beverages" },
            { name: "Apples", price: 2.44, category: "Fruit" },
            { name: "Steak", price: 1.99, category: "Other" },
            { name: "Eggs", price: 2.44, category: "Other" },
            { name: "Mushrooms", price: 1.99, category: "Other" },
            { name: "Yogurt", price: 2.44, category: "Other" },
            { name: "Soup", price: 1.99, category: "Other" },
            { name: "Cereal", price: 2.44, category: "Other" },
            { name: "Pepsi", price: 1.99, category: "Beverages" }
        ]);

    // Create grouped data source
    var groupedProducts = products.createGrouped(
        function (dataItem) {
            return dataItem.category;
        },
        function (dataItem) {
            return { title: dataItem.category };
        },
        function (group1, group2) {
            return group1.charCodeAt(0) - group2.charCodeAt(0);
        }
    );

    // Expose the grouped data source
    WinJS.Namespace.define("ListViewDemos", {
        products: groupedProducts
    });
})();
</pre>
<p>Notice that the createGrouped() method requires three functions as arguments: </p>
<ol>
<li>groupKey – This function associates each list item with a group. The function accepts a data item and returns a key which represents a group. In the code above, we return the value of the category property for each product.
<li>groupData – This function returns the data item displayed by the group header template. For example, in the code above, the function returns a <i>title</i> for the group which is displayed in the group header template.
<li>groupSorter – This function determines the order in which the groups are displayed. The code above displays the groups in alphabetical order: Beverages, Fruit, Other. </li>
</ol>
<h4>Creating the Group Header Template</h4>
<p>Whenever you create a ListView control, you need to create an item template which you use to control how each list item is rendered. When grouping items in a ListView control, you also need to create a group header template. The group header template is used to render the header for each group of list items. </p>
<p>Here’s the markup for both the item template and the group header template:
<pre class="brush: xml;">&lt;div id="productTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="product"&gt;
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;div id="productGroupHeaderTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="productGroupHeader"&gt;
        &lt;h1 data-win-bind="innerText: title"&gt;&lt;/h1&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>You should declare the two templates in the same file as you declare the ListView control – for example, the default.html file. </p>
<h4>Declaring the ListView Control</h4>
<p>The final step is to declare the ListView control. Here’s the required markup:
<pre class="brush: xml;">&lt;div data-win-control="WinJS.UI.ListView"
    data-win-options="{
        itemDataSource:ListViewDemos.products.dataSource,
        itemTemplate:select('#productTemplate'),
        groupDataSource:ListViewDemos.products.groups.dataSource,
        groupHeaderTemplate:select('#productGroupHeaderTemplate'),
        layout: {type: WinJS.UI.GridLayout}
    }"&gt;
&lt;/div&gt;
</pre>
<p>In the markup above, six properties of the ListView control are set when the control is declared. First the itemDataSource and itemTemplate are specified. Nothing new here. </p>
<p>Next, the group data source and group header template are specified. Notice that the group data source is represented by the ListViewDemos.products.groups.dataSource property of the grouped data source. </p>
<p>Finally, notice that the layout of the ListView is changed to Grid Layout. You are required to use Grid Layout (instead of the default List Layout) when displaying grouped items in a ListView. </p>
<p>Here’s the entire contents of the default.html page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;ListViewDemos&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- ListViewDemos references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
    &lt;script src="/js/products.js" type="text/javascript"&gt;&lt;/script&gt;

    &lt;style type="text/css"&gt;

        .product {
            width:  200px;
            height:  100px;
            border:  white solid 1px;
            font-size:  x-large;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id="productTemplate" data-win-control="WinJS.Binding.Template"&gt;
        &lt;div class="product"&gt;
            &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
            &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div id="productGroupHeaderTemplate" data-win-control="WinJS.Binding.Template"&gt;
        &lt;div class="productGroupHeader"&gt;
            &lt;h1 data-win-bind="innerText: title"&gt;&lt;/h1&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;div data-win-control="WinJS.UI.ListView"
        data-win-options="{
            itemDataSource:ListViewDemos.products.dataSource,
            itemTemplate:select('#productTemplate'),
            groupDataSource:ListViewDemos.products.groups.dataSource,
            groupHeaderTemplate:select('#productGroupHeaderTemplate'),
            layout: {type: WinJS.UI.GridLayout}
        }"&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Notice that the default.html page includes a reference to the products.js file: </p>
<p>&lt;script src=&#8221;/js/products.js&#8221; type=&#8221;text/javascript&#8221;&gt;&lt;/script&gt; </p>
<p>The default.html page also contains the declarations of the item template, group header template, and ListView control. </p>
<h4>Summary</h4>
<p>The goal of this blog entry was to explain how you can group items in a ListView control. You learned how to create a grouped data source, a group header template, and declare a ListView so that it groups its list items.</p>
<ol></ol>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=_qbAByxPzNI:HeNdoTmH4rE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/_qbAByxPzNI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/18/metro-grouping-items-in-a-listview-control.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/18/metro-grouping-items-in-a-listview-control.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Introduction to the WinJS ListView Control</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/7CvGrCXSH94/metro-introduction-to-the-winjs-listview-control.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/18/metro-introduction-to-the-winjs-listview-control.aspx#comments</comments>
		<pubDate>Fri, 18 May 2012 17:15:57 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=517</guid>
		<description><![CDATA[The goal of this blog entry is to provide a quick introduction to the ListView control – just the bare minimum that you need to know to start using the control. When building Metro style applications using JavaScript, the ListView control is the primary control that you use for displaying lists of items. For example, [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog entry is to provide a quick introduction to the ListView control – just the bare minimum that you need to know to start using the control. When building Metro style applications using JavaScript, the ListView control is the primary control that you use for displaying lists of items. For example, if you are building a product catalog app, then you can use the ListView control to display the list of products.
<p>The ListView control supports several advanced features that I plan to discuss in future blog entries. For example, you can group the items in a ListView, you can create master/details views with a ListView, and you can efficiently work with large sets of items with a ListView. In this blog entry, we’ll keep things simple and focus on displaying a list of products.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image_thumb.png" width="941" height="603"></a>
<p>There are three things that you need to do in order to display a list of items with a ListView:
<ol>
<li>Create a data source
<li>Create an Item Template
<li>Declare the ListView </li>
</ol>
<h4>Creating the ListView Data Source</h4>
<p>The first step is to create (or retrieve) the data that you want to display with the ListView. In most scenarios, you will want to bind a ListView to a WinJS.Binding.List object.
<p>The nice thing about the WinJS.Binding.List object is that it enables you to take a standard JavaScript array and convert the array into something that can be bound to the ListView. It doesn’t matter where the JavaScript array comes from. It could be a static array that you declare or you could retrieve the array as the result of an Ajax call to a remote server.
<p>The following JavaScript file – named products.js – contains a list of products which can be bound to a ListView.
<pre class="brush: js;">(function () {
    "use strict";

    var products = new WinJS.Binding.List([
            { name: "Milk", price: 2.44 },
            { name: "Oranges", price: 1.99 },
            { name: "Wine", price: 8.55 },
            { name: "Apples", price: 2.44 },
            { name: "Steak", price: 1.99 },
            { name: "Eggs", price: 2.44 },
            { name: "Mushrooms", price: 1.99 },
            { name: "Yogurt", price: 2.44 },
            { name: "Soup", price: 1.99 },
            { name: "Cereal", price: 2.44 },
            { name: "Pepsi", price: 1.99 }
        ]);

    WinJS.Namespace.define("ListViewDemos", {
        products: products
    });

})();
</pre>
<p>The <i>products</i> variable represents a WinJS.Binding.List object. This object is initialized with a plain-old JavaScript array which represents an array of products. </p>
<p>To avoid polluting the global namespace, the code above uses the module pattern and exposes the products using a namespace. The list of products is exposed to the world as ListViewDemos.products. </p>
<p>To learn more about the module pattern and namespaces in WinJS, see my earlier blog entry: </p>
<blockquote>
<p><a href="http://stephenwalther.com/blog/archive/2012/02/22/metro-namespaces-and-modules.aspx">http://stephenwalther.com/blog/archive/2012/02/22/metro-namespaces-and-modules.aspx</a> </p>
</blockquote>
<h4>Creating the ListView Item Template</h4>
<p>The ListView control does not know how to render anything. It doesn’t know how you want each list item to appear. To get the ListView control to render something useful, you must create an Item Template. </p>
<p>Here’s what our template for rendering an individual product looks like:
<pre class="brush: xml;">&lt;div id="productTemplate" data-win-control="WinJS.Binding.Template"&gt;
    &lt;div class="product"&gt;
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>This template displays the product name and price from the data source.</p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image1.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/image_thumb1.png" width="364" height="148"></a></p>
<p>Normally, you will declare your template in the same file as you declare the ListView control. In our case, both the template and ListView are declared in the default.html file. </p>
<p>To learn more about templates, see my earlier blog entry: </p>
<blockquote>
<p><a href="http://stephenwalther.com/blog/archive/2012/02/27/metro-using-templates.aspx">http://stephenwalther.com/blog/archive/2012/02/27/metro-using-templates.aspx</a> </p>
</blockquote>
<h4>Declaring the ListView</h4>
<p>The final step is to declare the ListView control in a page. Here’s the markup for declaring a ListView:
<pre class="brush: xml;">&lt;div data-win-control="WinJS.UI.ListView"
     data-win-options="{
        itemDataSource:ListViewDemos.products.dataSource,
        itemTemplate:select('#productTemplate')
     }"&gt;
&lt;/div&gt;
</pre>
<p>You declare a ListView by adding the data-win-control to an HTML DIV tag. The data-win-options attribute is used to set two properties of the ListView. </p>
<p>The ListView is associated with its data source with the itemDataSource property. Notice that the data source is ListViewDemos.products.dataSource and not just ListViewDemos.products. You need to associate the ListView with the dataSoure property. </p>
<p>The ListView is associated with its item template with the help of the itemTemplate property. The ID of the item template &#8212; #productTemplate – is used to select the template from the page. </p>
<p>Here’s what the complete version of the default.html page looks like:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;ListViewDemos&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- ListViewDemos references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
    &lt;script src="/js/products.js" type="text/javascript"&gt;&lt;/script&gt;

    &lt;style type="text/css"&gt;

        .product {
            width:  200px;
            height:  100px;
            border:  white solid 1px;
        }
    &lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div id="productTemplate" data-win-control="WinJS.Binding.Template"&gt;
        &lt;div class="product"&gt;
            &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
            &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div data-win-control="WinJS.UI.ListView"
            data-win-options="{
            itemDataSource:ListViewDemos.products.dataSource,
            itemTemplate:select('#productTemplate')
            }"&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Notice that the page above includes a reference to the products.js file: </p>
<blockquote>
<p>&lt;script src=&#8221;/js/products.js&#8221; type=&#8221;text/javascript&#8221;&gt;&lt;/script&gt; </p>
</blockquote>
<p>The page above also contains a Template control which contains the ListView item template. Finally, the page includes the declaration of the ListView control. </p>
<h4>Summary</h4>
<p>The goal of this blog entry was to describe the minimal set of steps which you must complete to use the WinJS ListView control to display a simple list of items. You learned how to create a data source, declare an item template, and declare a ListView control.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=7CvGrCXSH94:BLgznA51DWU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/7CvGrCXSH94" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/18/metro-introduction-to-the-winjs-listview-control.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/18/metro-introduction-to-the-winjs-listview-control.aspx</feedburner:origLink></item>
		<item>
		<title>Ajax Control Toolkit May 2012 Release</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/C-nTqgH2SCs/ajax-control-toolkit-may-2012-release.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx#comments</comments>
		<pubDate>Tue, 01 May 2012 16:46:46 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[ACT]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=509</guid>
		<description><![CDATA[I’m happy to announce the May 2012 release of the Ajax Control Toolkit. This newest release of the Ajax Control Toolkit includes a new file upload control which displays file upload progress. We’ve also added several significant enhancements to the existing HtmlEditorExtender control such as support for uploading images and Source View. You can download [...]]]></description>
			<content:encoded><![CDATA[<p>I’m happy to announce the May 2012 release of the Ajax Control Toolkit. This newest release of the Ajax Control Toolkit includes a new file upload control which displays file upload progress. We’ve also added several significant enhancements to the existing HtmlEditorExtender control such as support for uploading images and Source View.
<p>You can download and start using the newest version of the Ajax Control Toolkit by entering the following command in the Library Package Manager console in Visual Studio:
<p>Install-Package AjaxControlToolkit
<p>Alternatively, you can download the latest version of the Ajax Control Toolkit from CodePlex:
<p><a href="http://AjaxControlToolkit.CodePlex.com">http://AjaxControlToolkit.CodePlex.com</a><br />
<h3>The New Ajax File Upload Control</h3>
<p>The most requested new feature for the Ajax Control Toolkit (according to the CodePlex Issue Tracker) has been support for file upload with progress. We worked hard over the last few months to create an entirely new file upload control which displays upload progress.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002_thumb.jpg" width="628" height="255"></a>
<p>Here is a sample which illustrates how you can use the new AjaxFileUpload control:
<pre class="brush: xml;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="01_FileUpload.aspx.cs" Inherits="WebApplication1._01_FileUpload" %&gt;
&lt;html&gt;
&lt;head runat="server"&gt;
    &lt;title&gt;Simple File Upload&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;

    &lt;ajaxToolkit:ToolkitScriptManager runat="server" /&gt;

    &lt;ajaxToolkit:AjaxFileUpload
        id="ajaxUpload1"
        OnUploadComplete="ajaxUpload1_OnUploadComplete"
        runat="server"  /&gt;

    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The page above includes a ToolkitScriptManager control. This control is required to use any of the controls in the Ajax Control Toolkit because this control is responsible for loading all of the scripts required by a control. </p>
<p>The page also contains an AjaxFileUpload control. The UploadComplete event is handled in the code-behind for the page:
<pre class="brush: csharp;">namespace WebApplication1
{
    public partial class _01_FileUpload : System.Web.UI.Page
    {
        protected void ajaxUpload1_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            // Generate file path
            string filePath = "~/Images/" + e.FileName;

            // Save upload file to the file system
            ajaxUpload1.SaveAs(MapPath(filePath));
        }
    }
}
</pre>
<p>The UploadComplete handler saves each uploaded file by calling the AjaxFileUpload control’s SaveAs() method with a full file path. </p>
<p>Here’s a video which illustrates the process of uploading a file: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003.gif"><img style="display: inline" title="clip_image003" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003_thumb.gif" width="800" height="600"></a> </p>
<p>Warning: in order to write to the Images folder on a production IIS server, you need Write permissions on the Images folder. You need to provide permissions for the IIS Application Pool account to write to the Images folder. To learn more, see: </p>
<p><a href="http://learn.iis.net/page.aspx/624/application-pool-identities/">http://learn.iis.net/page.aspx/624/application-pool-identities/</a> </p>
<h4>Showing File Upload Progress</h4>
<p>The new AjaxFileUpload control takes advantage of HTML5 upload progress events (described in the <a href="http://www.w3.org/TR/XMLHttpRequest2/">XMLHttpRequest Level 2</a> standard). This standard is supported by Firefox 8+, Chrome 16+, Safari 5+, and Internet Explorer 10+. In other words, the standard is supported by the most recent versions of all browsers except for Internet Explorer which will support the standard with the release of Internet Explorer 10. </p>
<p>The AjaxFileUpload control works with all browsers, even browsers which do not support the new XMLHttpRequest Level 2 standard. If you use the AjaxFileUpload control with a downlevel browser – such as Internet Explorer 9 &#8212; then you get a simple throbber image during a file upload instead of a progress indicator. </p>
<p>Here’s how you specify a throbber image when declaring the AjaxFileUpload control:
<pre class="brush: xml;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="02_FileUpload.aspx.cs" Inherits="WebApplication1._02_FileUpload" %&gt;
&lt;html&gt;
&lt;head id="Head1" runat="server"&gt;
    &lt;title&gt;File Upload with Throbber&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;

    &lt;ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" /&gt;

    &lt;ajaxToolkit:AjaxFileUpload
        id="ajaxUpload1"
        OnUploadComplete="ajaxUpload1_OnUploadComplete"
        ThrobberID="MyThrobber"
        runat="server"  /&gt;

        &lt;asp:Image
            id="MyThrobber"
            ImageUrl="ajax-loader.gif"
            Style="display:None"
            runat="server" /&gt;

    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Notice that the page above includes an image with the Id MyThrobber. This image is displayed while files are being uploaded. </p>
<p>I use the website <a href="http://AjaxLoad.info">http://AjaxLoad.info</a> to generate animated busy wait images. </p>
<h4>Drag-And-Drop File Upload</h4>
<p>If you are using an uplevel browser then you can drag-and-drop the files which you want to upload onto the AjaxFileUpload control. The following video illustrates how drag-and-drop works: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image004.gif"><img style="display: inline" title="clip_image004" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image004_thumb.gif" width="800" height="600"></a> </p>
<p>Remember that drag-and-drop <i>will not</i> work on Internet Explorer 9 or older. </p>
<h4>Accepting Multiple Files</h4>
<p>By default, the AjaxFileUpload control enables you to upload multiple files at a time. When you open the file dialog, use the CTRL or SHIFT key to select multiple files. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image005.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image005" border="0" alt="clip_image005" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image005_thumb.png" width="629" height="658"></a> </p>
<p>If you want to restrict the number of files that can be uploaded then use the MaximumNumberOfFiles property like this:
<pre class="brush: xml;">&lt;ajaxToolkit:AjaxFileUpload
    id="ajaxUpload1"
    OnUploadComplete="ajaxUpload1_OnUploadComplete"
    ThrobberID="throbber"
    MaximumNumberOfFiles="1"
    runat="server"  /&gt;
</pre>
<p>In the code above, the maximum number of files which can be uploaded is restricted to a single file. </p>
<h4>Restricting Uploaded File Types </h4>
<p>You might want to allow only certain types of files to be uploaded. For example, you might want to accept only image uploads. In that case, you can use the AllowedFileTypes property to provide a list of allowed file types like this:
<pre class="brush: xml;">&lt;ajaxToolkit:AjaxFileUpload
    id="ajaxUpload1"
    OnUploadComplete="ajaxUpload1_OnUploadComplete"
    ThrobberID="throbber"
    AllowedFileTypes="jpg,jpeg,gif,png"
    runat="server"  /&gt;
</pre>
<p>The code above prevents any files except jpeg, gif, and png files from being uploaded. </p>
<h3>Enhancements to the HTMLEditorExtender</h3>
<p>Over the past months, we spent a considerable amount of time making bug fixes and feature enhancements to the existing HtmlEditorExtender control. I want to focus on two of the most significant enhancements that we made to the control: support for Source View and support for uploading images. </p>
<h4>Adding Source View Support to the HtmlEditorExtender</h4>
<p>When you click the Source View tag, the HtmlEditorExtender changes modes and displays the HTML source of the contents contained in the TextBox being extended. You can use Source View to make fine-grain changes to HTML before submitting the HTML to the server. </p>
<p>For reasons of backwards compatibility, the Source View tab is disabled by default. To enable Source View, you need to declare your HtmlEditorExtender with the DisplaySourceTab property like this:
<pre class="brush: xml;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="05_SourceView.aspx.cs" Inherits="WebApplication1._05_SourceView" %&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html&gt;
&lt;head id="Head1" runat="server"&gt;
    &lt;title&gt;HtmlEditorExtender with Source View&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;

    &lt;ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" /&gt;

    &lt;asp:TextBox
        id="txtComments"
        TextMode="MultiLine"
        Columns="60"
        Rows="10"
        Runat="server" /&gt;

    &lt;ajaxToolkit:HtmlEditorExtender
        id="HEE1"
        TargetControlID="txtComments"
        DisplaySourceTab="true"
        runat="server"  /&gt;

    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The page above includes a ToolkitScriptManager, TextBox, and HtmlEditorExtender control. The HtmlEditorExtender extends the TextBox so that it supports rich text editing. </p>
<p>Notice that the HtmlEditorExtender includes a DisplaySourceTab property. This property causes a button to appear at the bottom of the HtmlEditorExtender which enables you to switch to Source View: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image006.gif"><img style="display: inline" title="clip_image006" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image006_thumb.gif" width="800" height="600"></a> </p>
<p>Note: when using the HtmlEditorExtender, we recommend that you set the DOCTYPE for the document. Otherwise, you can encounter weird formatting issues. </p>
<h4>Accepting Image Uploads</h4>
<p>We also enhanced the HtmlEditorExtender to support image uploads (another very highly requested feature at CodePlex). The following video illustrates the experience of adding an image to the editor: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image007.gif"><img style="display: inline" title="clip_image007" alt="clip_image007" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image007_thumb.gif" width="800" height="600"></a> </p>
<p>Once again, for backwards compatibility reasons, support for image uploads is disabled by default. Here’s how you can declare the HtmlEditorExtender so that it supports image uploads:
<pre class="brush: xml;">&lt;ajaxToolkit:HtmlEditorExtender
    id="MyHtmlEditorExtender"
    TargetControlID="txtComments"
    OnImageUploadComplete="MyHtmlEditorExtender_ImageUploadComplete"
    DisplaySourceTab="true"
    runat="server" &gt;
    &lt;Toolbar&gt;
        &lt;ajaxToolkit:Bold /&gt;
        &lt;ajaxToolkit:Italic /&gt;
        &lt;ajaxToolkit:Underline /&gt;
        &lt;ajaxToolkit:InsertImage /&gt;
    &lt;/Toolbar&gt;
&lt;/ajaxToolkit:HtmlEditorExtender&gt;
</pre>
<p>There are two things that you should notice about the code above. First, notice that an InsertImage toolbar button is added to the HtmlEditorExtender toolbar. This HtmlEditorExtender will render toolbar buttons for bold, italic, underline, and insert image. </p>
<p>Second, notice that the HtmlEditorExtender includes an event handler for the ImageUploadComplete event. The code for this event handler is below:
<pre class="brush: csharp;">using System.Web.UI;
using AjaxControlToolkit;

namespace WebApplication1
{
    public partial class _06_ImageUpload : System.Web.UI.Page
    {

        protected void MyHtmlEditorExtender_ImageUploadComplete(object sender, AjaxFileUploadEventArgs e)
        {
            // Generate file path
            string filePath = "~/Images/" + e.FileName;

            // Save uploaded file to the file system
            var ajaxFileUpload = (AjaxFileUpload)sender;
            ajaxFileUpload.SaveAs(MapPath(filePath));

            // Update client with saved image path
            e.PostedUrl = Page.ResolveUrl(filePath);
        }
    }
}
</pre>
<p>Within the ImageUploadComplete event handler, you need to do two things: </p>
<p>1) Save the uploaded image (for example, to the file system, a database, or Azure storage) </p>
<p>2) Provide the URL to the saved image so the image can be displayed within the HtmlEditorExtender </p>
<p>In the code above, the uploaded image is saved to the ~/Images folder. The path of the saved image is returned to the client by setting the AjaxFileUploadEventArgs PostedUrl property. </p>
<p>Not surprisingly, under the covers, the HtmlEditorExtender uses the AjaxFileUpload. You can get a direct reference to the AjaxFileUpload control used by an HtmlEditorExtender by using the following code:
<pre class="brush: csharp;">void Page_Load()
{
    var ajaxFileUpload = MyHtmlEditorExtender.AjaxFileUpload;
    ajaxFileUpload.AllowedFileTypes = "jpg,jpeg";
}
</pre>
<p>The code above illustrates how you can restrict the types of images that can be uploaded to the HtmlEditorExtender. This code prevents anything but jpeg images from being uploaded. </p>
<h3>Summary</h3>
<p>This was the most difficult release of the Ajax Control Toolkit to date. We iterated through several designs for the AjaxFileUpload control – with each iteration, the goal was to make the AjaxFileUpload control easier for developers to use. My hope is that we were able to create a control which Web Forms developers will find very intuitive. </p>
<p>I want to thank the developers on the Superexpert.com team for their hard work on this release.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=C-nTqgH2SCs:O8opVesil9M:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/C-nTqgH2SCs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx</feedburner:origLink></item>
		<item>
		<title>ASP.NET Connections Spring 2012 Talks and Code</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/D20Z2ceY5n0/asp-net-connections-spring-2012-talks-and-code.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/04/09/asp-net-connections-spring-2012-talks-and-code.aspx#comments</comments>
		<pubDate>Mon, 09 Apr 2012 12:13:57 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Talks]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=493</guid>
		<description><![CDATA[Thank you everyone who attended my ASP.NET Connections talks last week in Las Vegas. I’ve attached the slides and code for the three talks that I delivered: &#160; Using jQuery to interact with the Server through Ajax – In this talk, I discuss the different ways to communicate information between browser and server using Ajax. [...]]]></description>
			<content:encoded><![CDATA[<p>Thank you everyone who attended my ASP.NET Connections talks last week in Las Vegas. I’ve attached the slides and code for the three talks that I delivered:</p>
<p>&nbsp;</p>
<ul>
<li><a href="/downloads/Talks/ASPNETConnectionsSpring2012/Walther_jQueryAjax.zip">Using jQuery to interact with the Server through Ajax</a> – In this talk, I discuss the different ways to communicate information between browser and server using Ajax. I explain the difference between the different types of Ajax calls that you can make with jQuery. I also discuss the differences between the JavaScriptSerializer, the DataContractJsonSerializer, and the JSON.NET serializer.
<p>&nbsp;</p>
<li><a href="/downloads/Talks/ASPNETConnectionsSpring2012/Walther_MVCValidation.zip">ASP.NET Validation In-Depth</a> – In this talk, I distinguish between View Model Validation and Domain Model Validation. I demonstrate how you can use the validation attributes (including the new .NET 4.5 validation attributes), the jQuery Validation library, and the HTML5 input validation attributes to perform View Model Validation. I then demonstrate how you can use the IValidatableObject interface with the Entity Framework to perform Domain Model Validation.
<p>&nbsp;</p>
<li><a href="/downloads/Talks/ASPNETConnectionsSpring2012/Walther_MVVM.zip">Using the MVVM Pattern with JavaScript Views</a> – In this talk, I discuss how you can create single page applications (SPA) by taking advantage of the open-source KnockoutJS library and the ASP.NET Web API. </li>
</ul>
<p>&nbsp;</p>
<p>Be warned that the sample code is contained in Visual Studio 11 Beta projects. If you don’t have this version of Visual Studio, then you will need to open the code samples in Notepad.</p>
<p>Also, I apologize for getting the code for these talks posted so slowly. I’ve been down with a nasty case of the flu for the past week and haven’t been able to get to a computer.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=D20Z2ceY5n0:o7OV_qQ3nOA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/D20Z2ceY5n0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/04/09/asp-net-connections-spring-2012-talks-and-code.aspx/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/04/09/asp-net-connections-spring-2012-talks-and-code.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Introduction to CSS 3 Grid Layout</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/UXt3Tc7yYsU/metro-introduction-to-css-3-grid-layout.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/03/19/metro-introduction-to-css-3-grid-layout.aspx#comments</comments>
		<pubDate>Tue, 20 Mar 2012 00:01:22 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=490</guid>
		<description><![CDATA[The purpose of this blog post is to provide you with a quick introduction to the new W3C CSS 3 Grid Layout standard. You can use CSS Grid Layout in Metro style applications written with JavaScript to lay out the content of an HTML page. CSS Grid Layout provides you with all of the benefits [...]]]></description>
			<content:encoded><![CDATA[<p>The purpose of this blog post is to provide you with a quick introduction to the new W3C CSS 3 Grid Layout standard. You can use CSS Grid Layout in Metro style applications written with JavaScript to lay out the content of an HTML page. CSS Grid Layout provides you with all of the benefits of using HTML tables for layout without requiring you to actually use any HTML table elements.<br />
<h3>Doing Page Layouts without Tables</h3>
<p>Back in the 1990’s, if you wanted to create a fancy website, then you would use HTML tables for layout. For example, if you wanted to create a standard three-column page layout then you would create an HTML table with three columns like this:
<pre class="brush: xml;">&lt;table height="100%"&gt;
&lt;tr&gt;
  &lt;td valign="top" width="300px" bgcolor="red"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/td&gt;
  &lt;td valign="top" bgcolor="green"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/td&gt;
  &lt;td valign="top" width="300px" bgcolor="blue"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
</pre>
<p>When the table above gets rendered out to a browser, you end up with the following three-column layout: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002_thumb.jpg" width="628" height="279"></a> </p>
<p>The width of the left and right columns is fixed – the width of the middle column expands or contracts depending on the width of the browser. </p>
<p>Sometime around the year 2005, everyone decided that using tables for layout was a bad idea. Instead of using tables for layout &#8212; it was collectively decided by the spirit of the Web &#8212; you should use Cascading Style Sheets instead. </p>
<p>Why is using HTML tables for layout bad? Using tables for layout breaks the semantics of the TABLE element. A TABLE element should be used only for displaying tabular information such as train schedules or moon phases. Using tables for layout is bad for accessibility (The Web Content Accessibility Guidelines 1.0 is explicit about this) and using tables for layout is bad for separating content from layout (see <a href="http://CSSZenGarden.com">http://CSSZenGarden.com</a>). </p>
<p>Post 2005, anyone who used HTML tables for layout were encouraged to hold their heads down in shame. </p>
<p>That’s all well and good, but the problem with using CSS for layout is that it can be more difficult to work with CSS than HTML tables. For example, to achieve a standard three-column layout, you either need to use absolute positioning or floats. Here’s a three-column layout with floats:
<pre class="brush: xml;">&lt;style type="text/css"&gt;
#container {
  min-width: 800px;
}

#leftColumn {
  float: left;
  width: 300px;
  height: 100%;
  background-color:red;
}

#middleColumn {
  background-color:green;
  height: 100%;
}

#rightColumn {
  float: right;
  width: 300px;
  height: 100%;
  background-color:blue;
}
&lt;/style&gt;

&lt;div id="container"&gt;
  &lt;div id="rightColumn"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/div&gt;
  &lt;div id="leftColumn"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/div&gt;
  &lt;div id="middleColumn"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/div&gt;
&lt;/div&gt; 
</pre>
<p>The page above contains four DIV elements: a container DIV which contains a leftColumn, middleColumn, and rightColumn DIV. The leftColumn DIV element is floated to the left and the rightColumn DIV element is floated to the right. Notice that the rightColumn DIV appears in the page before the middleColumn DIV – this unintuitive ordering is necessary to get the floats to work correctly (see <a href="http://stackoverflow.com/questions/533607/css-three-column-layout-problem">http://stackoverflow.com/questions/533607/css-three-column-layout-problem</a>). </p>
<p>The page above (almost) works with the most recent versions of most browsers. For example, you get the correct three-column layout in both Firefox and Chrome: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0041.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004_thumb1.jpg" width="628" height="263"></a> </p>
<p>And the layout mostly works with Internet Explorer 9 except for the fact that for some strange reason the min-width doesn’t work so when you shrink the width of your browser, you can get the following unwanted layout: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0061.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006_thumb1.jpg" width="628" height="191"></a> </p>
<p>Notice how the middle column (the green column) bleeds to the left and right. </p>
<p>People have solved these issues with more complicated CSS. For example, see: </p>
<p><a href="http://matthewjamestaylor.com/blog/holy-grail-no-quirks-mode.htm">http://matthewjamestaylor.com/blog/holy-grail-no-quirks-mode.htm</a> </p>
<p>But, at this point, no one could argue that using CSS is easier or more intuitive than tables. It takes work to get a layout with CSS and we know that we could achieve the same layout more easily using HTML tables. </p>
<h3>Using CSS Grid Layout</h3>
<p>CSS Grid Layout is a new W3C standard which provides you with all of the benefits of using HTML tables for layout without the disadvantage of using an HTML TABLE element. In other words, CSS Grid Layout enables you to perform table layouts using pure Cascading Style Sheets. The CSS Grid Layout standard is still in a “Working Draft” state (it is not finalized) and it is located here: </p>
<p><a href="http://www.w3.org/TR/css3-grid-layout/">http://www.w3.org/TR/css3-grid-layout/</a> </p>
<p>The CSS Grid Layout standard is only supported by Internet Explorer 10 and there are no signs that any browser other than Internet Explorer will support this standard in the near future. This means that it is only practical to take advantage of CSS Grid Layout when building Metro style applications with JavaScript. </p>
<p>Here’s how you can create a standard three-column layout using a CSS Grid Layout:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

&lt;style type="text/css"&gt;

html, body, #container {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100%;
}

#leftColumn {
  -ms-grid-column: 1;
  background-color:red;
}

#middleColumn {
  -ms-grid-column: 2;
  background-color:green;
}

#rightColumn {
  -ms-grid-column: 3;
  background-color:blue;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;
  &lt;div id="leftColumn"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/div&gt;
  &lt;div id="middleColumn"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/div&gt;
  &lt;div id="rightColumn"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When the page above is rendered in Internet Explorer 10, you get a standard three-column layout: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image008" border="0" alt="clip_image008" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008_thumb.jpg" width="628" height="339"></a> </p>
<p>The page above contains four DIV elements: a container DIV which contains a leftColumn DIV, middleColumn DIV, and rightColumn DIV. </p>
<p>The container DIV is set to Grid display mode with the following CSS rule:
<pre class="brush: xml;">#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100%;
}
</pre>
<p>The display property is set to the value “-ms-grid”. This property causes the container DIV to lay out its child elements in a grid. </p>
<p>(Notice that you use “-ms-grid” instead of “grid”. The “-ms-“ prefix is used because the CSS Grid Layout standard is still preliminary. This implementation only works with IE10 and it might change before the final release.) </p>
<p>The grid columns and rows are defined with the “-ms-grid-columns” and “-ms-grid-rows” properties. The style rule above creates a grid with three columns and one row. The left and right columns are fixed sized at 300 pixels. The middle column sizes automatically depending on the remaining space available. </p>
<p>The leftColumn, middleColumn, and rightColumn DIVs are positioned within the container grid element with the following CSS rules:
<pre class="brush: xml;">#leftColumn {
  -ms-grid-column: 1;
  background-color:red;
}

#middleColumn {
  -ms-grid-column: 2;
  background-color:green;
}

#rightColumn {
  -ms-grid-column: 3;
  background-color:blue;
} 
</pre>
<p>The “-ms-grid-column” property is used to specify the column associated with the element selected by the style sheet selector. The leftColumn DIV is positioned in the first grid column, the middleColumn DIV is positioned in the second grid column, and the rightColumn DIV is positioned in the third grid column.</p>
<p>I find using CSS Grid Layout to be just as intuitive as using an HTML table for layout. You define your columns and rows and then you position different elements within these columns and rows. Very straightforward. </p>
<h3>Creating Multiple Columns and Rows</h3>
<p>In the previous section, we created a super simple three-column layout. This layout contained only a single row. In this section, let’s create a slightly more complicated layout which contains more than one row: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image010.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image010" border="0" alt="clip_image010" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image010_thumb.jpg" width="628" height="382"></a> </p>
<p>The following page contains a header row, a content row, and a footer row. The content row contains three columns:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

&lt;style type="text/css"&gt;

html, body, #container {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100px 1fr 100px;
}

#header {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 1;
  background-color: yellow;
}

#leftColumn {
  -ms-grid-column: 1;
  -ms-grid-row: 2;
  background-color:red;
}

#middleColumn {
  -ms-grid-column: 2;
  -ms-grid-row: 2;
  background-color:green;
}

#rightColumn {
  -ms-grid-column: 3;
  -ms-grid-row: 2;
  background-color:blue;
}

#footer {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 3;
  background-color: orange;
}

&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;
  &lt;div id="header"&gt;
    Header, Header, Header
  &lt;/div&gt;

  &lt;div id="leftColumn"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/div&gt;
  &lt;div id="middleColumn"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/div&gt;
  &lt;div id="rightColumn"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/div&gt;
  &lt;div id="footer"&gt;
    Footer, Footer, Footer
  &lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the page above, the grid layout is created with the following rule which creates a grid with three rows and three columns:
<pre class="brush: xml;">#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100px 1fr 100px;
}
</pre>
<p>The header is created with the following rule:
<pre class="brush: xml;">#header {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 1;
  background-color: yellow;
}
</pre>
<p>The header is positioned in column 1 and row 1. Furthermore, notice that the “-ms-grid-column-span” property is used to span the header across three columns. </p>
<h3>CSS Grid Layout and Fractional Units</h3>
<p>When you use CSS Grid Layout, you can take advantage of fractional units. Fractional units provide you with an easy way of dividing up remaining space in a page. </p>
<p>Imagine, for example, that you want to create a three-column page layout. You want the size of the first column to be fixed at 200 pixels and you want to divide the remaining space among the remaining three columns. The width of the second column is equal to the combined width of the third and fourth columns. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image012.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image012" border="0" alt="clip_image012" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image012_thumb.jpg" width="628" height="287"></a> </p>
<p>The following CSS rule creates four columns with the desired widths:
<pre class="brush: xml;">#container {
  display: -ms-grid;
  -ms-grid-columns: 200px 2fr 1fr 1fr;
  -ms-grid-rows: 1fr;
}  
</pre>
<p>The fr unit represents a fraction. The grid above contains four columns. The second column is two times the size (2fr) of the third (1fr) and fourth (1fr) columns. When you use the fractional unit, the remaining space is divided up using fractional amounts. </p>
<p>Notice that the single row is set to a height of 1fr. The single grid row gobbles up the entire vertical space. </p>
<p>Here’s the entire HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

&lt;style type="text/css"&gt;

html, body, #container {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#container {
  display: -ms-grid;
  -ms-grid-columns: 200px 2fr 1fr 1fr;
  -ms-grid-rows: 1fr;
}

#firstColumn {
  -ms-grid-column: 1;
  background-color:red;
}

#secondColumn {
  -ms-grid-column: 2;
  background-color:green;
}

#thirdColumn {
  -ms-grid-column: 3;
  background-color:blue;
}

#fourthColumn {
  -ms-grid-column: 4;
  background-color:orange;
}

&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;
  &lt;div id="firstColumn"&gt;
  First Column, First Column, First Column
  &lt;/div&gt;
  &lt;div id="secondColumn"&gt;
  Second Column, Second Column, Second Column
  &lt;/div&gt;
  &lt;div id="thirdColumn"&gt;
  Third Column, Third Column, Third Column
  &lt;/div&gt;
  &lt;div id="fourthColumn"&gt;
  Fourth Column, Fourth Column, Fourth Column
  &lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>&nbsp;<br />
<h3>Summary</h3>
<p>There is more in the CSS 3 Grid Layout standard than discussed in this blog post. My goal was to describe the basics. If you want to learn more than you can read through the entire standard at <a href="http://www.w3.org/TR/css3-grid-layout/">http://www.w3.org/TR/css3-grid-layout/</a> </p>
<p>In this blog post, I described some of the difficulties that you might encounter when attempting to replace HTML tables with Cascading Style Sheets when laying out a web page. I explained how you can take advantage of the CSS 3 Grid Layout standard to avoid these problems when building Metro style applications using JavaScript. CSS 3 Grid Layout provides you with all of the benefits of using HTML tables for laying out a page without requiring you to use HTML table elements.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=UXt3Tc7yYsU:Qtrx-_R3O2c:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/UXt3Tc7yYsU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/03/19/metro-introduction-to-css-3-grid-layout.aspx/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/03/19/metro-introduction-to-css-3-grid-layout.aspx</feedburner:origLink></item>
		<item>
		<title>HTML5 Form Validation</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/8RPvFaqnsmg/html5-form-validation.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx#comments</comments>
		<pubDate>Wed, 14 Mar 2012 03:27:59 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=476</guid>
		<description><![CDATA[The latest versions of Google Chrome (16+), Mozilla Firefox (8+), and Internet Explorer (10+) all support HTML5 client-side validation. It is time to take HTML5 validation seriously. The purpose of the blog post is to describe how you can take advantage of HTML5 client-side validation regardless of the type of application that you are building. [...]]]></description>
			<content:encoded><![CDATA[<p>The latest versions of Google Chrome (16+), Mozilla Firefox (8+), and Internet Explorer (10+) all support HTML5 client-side validation. It is time to take HTML5 validation seriously.
<p>The purpose of the blog post is to describe how you can take advantage of HTML5 client-side validation regardless of the type of application that you are building. You learn how to use the HTML5 validation attributes, how to perform custom validation using the JavaScript validation constraint API, and how to simulate HTML5 validation on older browsers by taking advantage of a jQuery plugin. Finally, we discuss the security issues related to using client-side validation.<br />
<h3>Using Client-Side Validation Attributes</h3>
<p>The HTML5 specification discusses several attributes which you can use with INPUT elements to perform client-side validation including the <i>required</i>, <i>pattern, min, max, step, and maxlength</i> attributes.
<p>For example, you use the <i>required</i> attribute to require a user to enter a value for an INPUT element. The following form demonstrates how you can make the firstName and lastName form fields required:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Required Demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;form&gt;
        &lt;label&gt;
            First Name:
            &lt;input required title="First Name is Required!" /&gt;
        &lt;/label&gt;
        &lt;label&gt;
            Last Name:
            &lt;input required title="Last Name is Required!" /&gt;
        &lt;/label&gt;
        &lt;button&gt;Register&lt;/button&gt;
    &lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If you attempt to submit this form without entering a value for firstName or lastName then you get the validation error message: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0011.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image001" border="0" alt="clip_image001" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image001_thumb1.png" width="617" height="237"></a> </p>
<p>Notice that the value of the title attribute is used to display the validation error message “First Name is Required!”. The title attribute does not work this way with the current version of Firefox. If you want to display a custom validation error message with Firefox then you need to include an x-moz-errormessage attribute like this:
<pre class="brush: xml;">&lt;input required title="First Name is Required!" 

     x-moz-errormessage="First Name is Required!" /&gt; 
</pre>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0021.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002_thumb1.png" width="604" height="229"></a> </p>
<p>The <i>pattern</i> attribute enables you to validate the value of an INPUT element against a regular expression. For example, the following form includes a social security number field which includes a <i>pattern</i> attribute:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Pattern&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;form&gt;
        &lt;label&gt;
            Social Security Number:
            &lt;input required pattern="^\d{3}-\d{2}-\d{4}$"
                title="###-##-####" /&gt;
        &lt;/label&gt;
        &lt;button&gt;Register&lt;/button&gt;
    &lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The regular expression in the form above requires the social security number to match the pattern ###-##-####: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image003.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image003" border="0" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image003_thumb.png" width="604" height="229"></a> </p>
<p>Notice that the input field includes both a <i>pattern</i> and a <i>required</i> validation attribute. If you don’t enter a value then the regular expression is never triggered. You need to include the <i>required</i> attribute to force a user to enter a value and cause the value to be validated against the regular expression. </p>
<h3>Custom Validation</h3>
<p>You can take advantage of the HTML5 constraint validation API to perform custom validation. You can perform any custom validation that you need. The only requirement is that you write a JavaScript function. </p>
<p>For example, when booking a hotel room, you might want to validate that the Arrival Date is in the future instead of the past:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Constraint Validation API&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;form&gt;
        &lt;label&gt;
            Arrival Date:
            &lt;input id="arrivalDate" type="date" required /&gt;
        &lt;/label&gt;
        &lt;button&gt;Submit Reservation&lt;/button&gt;
    &lt;/form&gt;

    &lt;script type="text/javascript"&gt;

        var arrivalDate = document.getElementById("arrivalDate");

        arrivalDate.addEventListener("input", function() {
            var value = new Date(arrivalDate.value);
            if (value &lt; new Date()) {
                arrivalDate.setCustomValidity("Arrival date must be after now!");
            } else {
                arrivalDate.setCustomValidity("");
            }

        });

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The form above contains an input field named arrivalDate. Entering a value into the arrivalDate field triggers the input event. </p>
<p>The JavaScript code adds an event listener for the input event and checks whether the date entered is greater than the current date. If validation fails then the validation error message “Arrival date must be after now!” is assigned to the arrivalDate input field by calling the setCustomValidity() method of the validation constraint API. Otherwise, the validation error message is cleared by calling setCustomValidity() with an empty string. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004_thumb.png" width="548" height="246"></a> </p>
<h3>HTML5 Validation and Older Browsers</h3>
<p>But what about older browsers? For example, what about Apple Safari and versions of Microsoft Internet Explorer older than Internet Explorer 10? </p>
<p>What the world really needs is a jQuery plugin which provides backwards compatibility for the HTML5 validation attributes. If a browser supports the HTML5 validation attributes then the plugin would do nothing. Otherwise, the plugin would add support for the attributes. </p>
<p>Unfortunately, as far as I know, this plugin does not exist. I have not been able to find any plugin which supports both the <i>required</i> and <i>pattern</i> attributes for older browsers, but does not get in the way of these attributes in the case of newer browsers. </p>
<p>There are several jQuery plugins which provide partial support for the HTML5 validation attributes including: </p>
<p>· jQuery Validation &#8212; <a href="http://docs.jquery.com/Plugins/Validation">http://docs.jquery.com/Plugins/Validation</a> </p>
<p>· html5Form &#8212; <a href="http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html">http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html</a> </p>
<p>· h5Validate &#8212; <a href="http://ericleads.com/h5validate/">http://ericleads.com/h5validate/</a> </p>
<p>The jQuery Validation plugin – the most popular JavaScript validation library – supports the HTML5 <i>required</i> attribute, but it does not support the HTML5 <i>pattern</i> attribute. Likewise, the html5Form plugin does not support the <i>pattern</i> attribute. </p>
<p>The h5Validate plugin provides the best support for the HTML5 validation attributes. The following page illustrates how this plugin supports both the <i>required</i> and <i>pattern</i> attributes:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;h5Validate&lt;/title&gt;
    &lt;style type="text/css"&gt;
        .validationError {
            border: solid 2px red;
        }
        .validationValid {
            border:  solid 2px green;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="customerForm"&gt;
        &lt;label&gt;
            First Name:
            &lt;input id="firstName" required /&gt;
        &lt;/label&gt;
        &lt;label&gt;
            Social Security Number:
            &lt;input id="ssn" required pattern="^\d{3}-\d{2}-\d{4}$"
                title="Expected pattern is ###-##-####" /&gt;
        &lt;/label&gt;
        &lt;input type="submit" /&gt;
    &lt;/form&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.4.4.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/jquery.h5validate.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        // Enable h5Validate plugin
        $("#customerForm").h5Validate({
            errorClass: "validationError",
            validClass: "validationValid"
        });

        // Prevent form submission when errors
        $("#customerForm").submit(function (evt) {
            if ($("#customerForm").h5Validate("allValid") === false) {
                evt.preventDefault();
            }
        });

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When an input field fails validation, the validationError CSS class is applied to the field and the field appears with a red border. When an input field passes validation, the validationValid CSS class is applied to the field and the field appears with a green border. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006_thumb.jpg" width="628" height="167"></a> </p>
<p>From the perspective of HTML5 validation, the h5Validate plugin is the best of the plugins. It adds support for the <i>required</i> and <i>pattern</i> attributes to browsers which do not natively support these attributes such as IE9. However, this plugin does not include everything in my wish list for a perfect HTML5 validation plugin. </p>
<p>Here’s my wish list for the perfect <i>back compat</i> HTML5 validation plugin: </p>
<p>1. The plugin would disable itself when used with a browser which natively supports HTML5 validation attributes. The plugin should not be too greedy – it should not handle validation when a browser could do the work itself. </p>
<p>2. The plugin should simulate the same user interface for displaying validation error messages as the user interface displayed by browsers which natively support HTML5 validation. Chrome, Firefox, and Internet Explorer all display validation errors in a popup. The perfect plugin would also display a popup. </p>
<p>3. Finally, the plugin would add support for the setCustomValidity() method and the other methods of the HTML5 validation constraint API. That way, you could implement custom validation in a standards compatible way and you would know that it worked across all browsers both old and new. </p>
<h3>Security</h3>
<p>It would be irresponsible of me to end this blog post without mentioning the issue of security. It is important to remember that any client-side validation &#8212; including HTML5 validation &#8212; can be bypassed. </p>
<p>You should use client-side validation with the intention to create a better user experience. Client validation is great for providing a user with immediate feedback when the user is in the process of completing a form. However, client-side validation cannot prevent an evil hacker from submitting unexpected form data to your web server. </p>
<p>You should always enforce your validation rules on the server. The only way to ensure that a required field has a value is to verify that the required field has a value on the server. The HTML5 <i>required</i> attribute does not guarantee anything. </p>
<h3>Summary</h3>
<p>The goal of this blog post was to describe the support for validation contained in the HTML5 standard. You learned how to use both the <i>required</i> and the <i>pattern</i> attributes in an HTML5 form. We also discussed how you can implement custom validation by taking advantage of the setCustomValidity() method. </p>
<p>Finally, I discussed the available jQuery plugins for adding support for the HTM5 validation attributes to older browsers. Unfortunately, I am unaware of any jQuery plugin which provides a perfect solution to the problem of backwards compatibility.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=8RPvFaqnsmg:cSImsWpY_DM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/8RPvFaqnsmg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx</feedburner:origLink></item>
		<item>
		<title>Introduction to the ASP.NET Web API</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/KKqqBS-mvWE/introduction-to-the-asp-net-web-api.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx#comments</comments>
		<pubDate>Mon, 05 Mar 2012 23:16:52 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=463</guid>
		<description><![CDATA[I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site &#8212; then you need to use Ajax. Otherwise, you are just being cruel to your customers. We use [...]]]></description>
			<content:encoded><![CDATA[<p>I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site &#8212; then you need to use Ajax. Otherwise, you are just being cruel to your customers.
<p>We use Ajax extensively in several of the ASP.NET applications that my company, <a href="http://superexpert.com">Superexpert.com</a>, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser.
<p>One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions.
<p>Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the <i>ASP.NET Web API</i>. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications.
<p>The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API.<br />
<h3>Creating an ASP.NET Web API Controller</h3>
<p>The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box.
<p>Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the <b>Empty API controller</b> template:
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image001.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image001" border="0" alt="clip_image001" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image001_thumb.png" width="608" height="397"></a>
<p>A brand new API controller looks like this:
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPIApp.Controllers
{
    public class MovieController : ApiController
    {
    }
}
</pre>
<p>An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class. </p>
<h3>Using jQuery to Retrieve, Insert, Update, and Delete Data</h3>
<p>Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this:
<pre class="brush: csharp;">namespace MyWebAPIApp.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Director { get; set; }
    }
}
</pre>
<p>Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page. </p>
<h4>Getting a Single Record with the ASP.NET Web API</h4>
<p>To support retrieving a single movie from the server, we need to add a Get method to our API controller:
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPIApp.Models;

namespace MyWebAPIApp.Controllers
{
    public class MovieController : ApiController
    {

        public Movie GetMovie(int id)
        {
            // Return movie by id
            if (id == 1)
            {
                return new Movie
                {
                    Id = 1,
                    Title = "Star Wars",
                    Director = "Lucas"
                };
            }

            // Otherwise, movie was not found
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
}
</pre>
<p>In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code. </p>
<p>After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: <a href="http://localhost:[port]/api/movie/1">http://localhost:[port]/api/movie/1</a> (You’ll need to enter the correct randomly generated port). </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002_thumb.png" width="283" height="435"></a> </p>
<p>In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE &#8212; is used to identify the action to invoke. </p>
<p>The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1. </p>
<p>The default route for the Web API is defined in the Global.asax file and it looks like this:
<pre class="brush: csharp;">routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</pre>
<p>We can invoke our GetMovie() controller action with the jQuery code in the following HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Get Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;div&gt;
        Title: &lt;span id="title"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
        Director: &lt;span id="director"&gt;&lt;/span&gt;
    &lt;/div&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt; 

        getMovie(1, function (movie) {
            $("#title").html(movie.Title);
            $("#director").html(movie.Director);
        });

        function getMovie(id, callback) {
            $.ajax({
                url: "/api/Movie",
                data: { id: id },
                type: "GET",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    200: function (movie) {
                        callback(movie);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page. </p>
<p>Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application). </p>
<p>You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004_thumb.jpg" width="628" height="404"></a> </p>
<h4>Getting a Set of Records with the ASP.NET Web API</h4>
<p>Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies:
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPIApp.Models;

namespace MyWebAPIApp.Controllers
{
    public class MovieController : ApiController
    {

        public IEnumerable&lt;Movie&gt; ListMovies()
        {
            return new List&lt;Movie&gt; {
                new Movie {Id=1, Title="Star Wars", Director="Lucas"},
                new Movie {Id=1, Title="King Kong", Director="Jackson"},
                new Movie {Id=1, Title="Memento", Director="Nolan"}
            };
        }

    }
}
</pre>
<p>Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method):
<pre class="brush: csharp;">routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</pre>
<p>This route enables us to invoke the ListMovies() method with the URL <a href="http://localhost:15296/api/movie/listmovies">/api/movie/listmovies</a>. </p>
<p>Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;List Movies&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;div id="movies"&gt;&lt;/div&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        listMovies(function (movies) {
            var strMovies="";
            $.each(movies, function (index, movie) {
                strMovies += "&lt;div&gt;" + movie.Title + "&lt;/div&gt;";
            });
            $("#movies").html(strMovies);

        });

        function listMovies(callback) {
            $.ajax({
                url: "/api/Movie/ListMovies",
                data: {},
                type: "GET",
                contentType: "application/json;charset=utf-8",
            }).then(function(movies){
                callback(movies);
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>&nbsp;
<p>&nbsp;
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image005.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image005" border="0" alt="clip_image005" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image005_thumb.png" width="595" height="679"></a> </p>
<h4>Inserting a Record with the ASP.NET Web API</h4>
<p>Now let’s modify our Movie API controller so it supports creating new records:
<pre class="brush: csharp;">public HttpResponseMessage&lt;Movie&gt; PostMovie(Movie movieToCreate)
{
    // Add movieToCreate to the database and update primary key
    movieToCreate.Id = 23;

    // Build a response that contains the location of the new movie
    var response = new HttpResponseMessage&lt;Movie&gt;(movieToCreate, HttpStatusCode.Created);
    var relativePath = "/api/movie/" + movieToCreate.Id;
    response.Headers.Location = new Uri(Request.RequestUri, relativePath);
    return response;
}
</pre>
<p>The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database. </p>
<p>When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response. </p>
<p>Because the name of our method starts with “Post&#8221;, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request. </p>
<p>The following HTML page invokes the PostMovie() method.
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Create Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        var movieToCreate = {
            title: "The Hobbit",
            director: "Jackson"
        };
        createMovie(movieToCreate, function (newMovie) {
            alert("New movie created with an Id of " + newMovie.Id);
        });

        function createMovie(movieToCreate, callback) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify( movieToCreate ),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    201: function (newMovie) {
                        callback(newMovie);
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006_thumb.png" width="595" height="679"></a> </p>
<p>The HTTP Post operation is performed with the following call to the jQuery $.ajax() method:
<pre class="brush: js;">$.ajax({
    url: "/api/Movie",
    data: JSON.stringify( movieToCreate ),
    type: "POST",
    contentType: "application/json;charset=utf-8",
    statusCode: {
        201: function (newMovie) {
            callback(newMovie);
        }
    }
});
</pre>
<p>Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method. </p>
<p>Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string. </p>
<p>Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code. </p>
<h4>Updating a Record with the ASP.NET Web API</h4>
<p>Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request:
<pre class="brush: csharp;">public void PutMovie(Movie movieToUpdate)
{
    if (movieToUpdate.Id == 1) {
        // Update the movie in the database
        return;
    }

    // If you can't find the movie to update
    throw new HttpResponseException(HttpStatusCode.NotFound);
}
</pre>
<p>Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404. </p>
<p>The following HTML page illustrates how you can invoke the PutMovie() method:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Put Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        var movieToUpdate = {
            id: 1,
            title: "The Hobbit",
            director: "Jackson"
        };
        updateMovie(movieToUpdate, function () {
            alert("Movie updated!");
        });

        function updateMovie(movieToUpdate, callback) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify(movieToUpdate),
                type: "PUT",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    200: function () {
                        callback();
                    },
                    404: function () {
                        alert("Movie not found!");
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h4>Deleting a Record with the ASP.NET Web API</h4>
<p>Here’s the code for deleting a movie:
<pre class="brush: csharp;">public HttpResponseMessage DeleteMovie(int id)
{
    // Delete the movie from the database

    // Return status code
    return new HttpResponseMessage(HttpStatusCode.NoContent);
}
</pre>
<p>This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204). </p>
<p>The following page illustrates how you can invoke the DeleteMovie() action:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Delete Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        deleteMovie(1, function () {
            alert("Movie deleted!");
        });

        function deleteMovie(id, callback) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify({id:id}),
                type: "DELETE",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    204: function () {
                        callback();
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>Performing Validation</h3>
<p>How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free. </p>
<p>Let’s modify our Movie class so it includes some of the standard validation attributes:
<pre class="brush: csharp;">using System.ComponentModel.DataAnnotations;
namespace MyWebAPIApp.Models
{
    public class Movie
    {
        public int Id { get; set; }

        [Required(ErrorMessage="Title is required!")]
        [StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")]
        public string Title { get; set; }

        [Required(ErrorMessage="Director is required!")]
        public string Director { get; set; }
    }
}
</pre>
<p>In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters. </p>
<p>Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database:
<pre class="brush: csharp;">public HttpResponseMessage PostMovie(Movie movieToCreate)
{
    // Validate movie
    if (!ModelState.IsValid)
    {
        var errors = new JsonArray();
        foreach (var prop in ModelState.Values)
        {
            if (prop.Errors.Any())
            {
                errors.Add(prop.Errors.First().ErrorMessage);
            }
        }
        return new HttpResponseMessage&lt;JsonValue&gt;(errors, HttpStatusCode.BadRequest);
    }

    // Add movieToCreate to the database and update primary key
    movieToCreate.Id = 23;

    // Build a response that contains the location of the new movie
    var response = new HttpResponseMessage&lt;Movie&gt;(movieToCreate, HttpStatusCode.Created);
    var relativePath = "/api/movie/" + movieToCreate.Id;
    response.Headers.Location = new Uri(Request.RequestUri, relativePath);
    return response;
}
</pre>
<p>If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property &#8212; can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code). </p>
<p>The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Create Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        var movieToCreate = {
            title: "The Hobbit",
            director: ""
        };

        createMovie(movieToCreate,
            function (newMovie) {
                alert("New movie created with an Id of " + newMovie.Id);
            },
            function (errors) {
                var strErrors = "";
                $.each(errors, function(index, err) {
                    strErrors += "*" + err + "\n";
                });
                alert(strErrors);
            }
        );

        function createMovie(movieToCreate, success, fail) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify(movieToCreate),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    201: function (newMovie) {
                        success(newMovie);
                    },
                    400: function (xhr) {
                        var errors = JSON.parse(xhr.responseText);
                        fail(errors);
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created. </p>
<p>If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image007.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image007" border="0" alt="clip_image007" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image007_thumb.png" width="356" height="133"></a> </p>
<p>(Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness) </p>
<p>This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action: </p>
<p><a href="http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation">http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation</a> </p>
<p>His validation filter looks like this:
<pre class="brush: csharp;">using System.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace MyWebAPIApp.Filters
{
    public class ValidationActionFilter:ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var modelState = actionContext.ModelState;
            if (!modelState.IsValid)
            {
                dynamic errors = new JsonObject();
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        errors[key] = state.Errors.First().ErrorMessage;
                    }
                }
                actionContext.Response = new HttpResponseMessage&lt;JsonValue&gt;(errors, HttpStatusCode.BadRequest);
            }
        }
    }
}
</pre>
<p>And you can register the validation filter in the Application_Start() method in the Global.asax file like this:
<pre class="brush: csharp;">GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter());
</pre>
<p>After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter. </p>
<h3>Querying using OData </h3>
<p>The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here: </p>
<p><a href="http://odata.org">http://odata.org</a> </p>
<p>For example, here are some of the query options which you can use with OData: </p>
<p>· $orderby – Enables you to retrieve results in a certain order. </p>
<p>· $top – Enables you to retrieve a certain number of results. </p>
<p>· $skip – Enables you to skip over a certain number of results (use with $top for paging). </p>
<p>· $filter – Enables you to filter the results returned. </p>
<p>The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable. </p>
<p>For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies:
<pre class="brush: csharp;">public IQueryable&lt;Movie&gt; GetMovies()
{
    return new List&lt;Movie&gt; {
        new Movie {Id=1, Title="Star Wars", Director="Lucas"},
        new Movie {Id=2, Title="King Kong", Director="Jackson"},
        new Movie {Id=3, Title="Willow", Director="Lucas"},
        new Movie {Id=4, Title="Shrek", Director="Smith"},
        new Movie {Id=5, Title="Memento", Director="Nolan"}
    }.AsQueryable();
}
</pre>
<p>If you enter the following URL in your browser: </p>
<p><a href="http://localhost:15296/api/movie?$top=2&amp;$orderby=Title">/api/movie?$top=2&amp;$orderby=Title</a> </p>
<p>Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image008" border="0" alt="clip_image008" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008_thumb.png" width="542" height="386"></a> </p>
<p>By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time.</p>
<p>The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples: </p>
<p><b>Return every movie directed by Lucas:</b> </p>
<p>/api/movie?$filter=Director eq &#8216;Lucas&#8217; </p>
<p><b>Return every movie which has a title which starts with ‘S’:</b> </p>
<p>/api/movie?$filter=startswith(Title,&#8217;S') </p>
<p><b>Return every movie which has an Id greater than 2:</b> </p>
<p>/api/movie?$filter=Id gt 2 </p>
<p>The complete documentation for the $filter option is located here: </p>
<p><a href="http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption">http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption</a> </p>
<h3>Summary</h3>
<p>The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API. </p>
<p>I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery. </p>
<p>Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option. </p>
<p>I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=KKqqBS-mvWE:rl3lORFi_80:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/KKqqBS-mvWE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx</feedburner:origLink></item>
	</channel>
</rss>

