<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Phil Derksen &#187; jQuery</title>
	<atom:link href="http://philderksen.com/category/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://philderksen.com</link>
	<description>Web Development, WordPress and SEO</description>
	<lastBuildDate>Thu, 02 Feb 2012 06:33:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Agile Zen, a web app built with ASP.NET MVC 2 and jQuery</title>
		<link>http://philderksen.com/2010/agile-zen-asp-net-mvc-2-jquery/</link>
		<comments>http://philderksen.com/2010/agile-zen-asp-net-mvc-2-jquery/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 21:16:48 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://philderksen.com/?p=221</guid>
		<description><![CDATA[I was fortunate enough to attend Microsoft's MIX conference for the first time this year. I learned a ton, jotted down hundreds of ideas for my projects, and had some valuable discussions with a lot of smart people.

Obviously you have to attend in person to network, but fortunately all the videos and slides are being made available online. Even for attendees this is great for review, but also because you inevitably miss a ton of sessions because of the schedule.

At the very end, I attended a great session by the co-founder and developer of Agile Zen, Nate Kohari. It's a unique project management web app written in ASP.NET MVC 2 and jQuery. ]]></description>
			<content:encoded><![CDATA[<p>I was fortunate enough to attend Microsoft&#8217;s <a href="http://live.visitmix.com/">MIX conference</a> for the first time this year. I learned a ton, jotted down hundreds of ideas for my projects, and had some valuable discussions with a lot of smart people.</p>
<p>Obviously you have to attend in person to network, but fortunately all the videos and slides are being made available online. Even for attendees this is great for review, but also because you inevitably miss a ton of sessions because of the schedule.</p>
<p>At the very end, I attended a great session by the co-founder and developer of <a href="http://www.agilezen.com/">Agile Zen</a>, <a href="http://twitter.com/nkohari">Nate Kohari</a>. It&#8217;s a unique project management web app written in ASP.NET MVC 2 and jQuery. Nate&#8217;s the sole developer and this is his major product. It&#8217;s a business that charges for certain levels of usage, not a free-to-use or open source app created for fun. It was refreshing to go through something more in line with my own goals. <a href="http://live.visitmix.com/MIX10/Sessions/EX10">See the video and slides for yourself</a>.</p>
<p>Some of the technology Zen is using:</p>
<ul>
<li>ASP.NET MVC 2</li>
<li>jQuery &amp; <a href="http://jqueryui.com/">jQuery UI</a></li>
<li><a href="http://jsclass.jcoglan.com/">JS.Class</a> (OO JavaScript)</li>
<li><a href="http://nhforge.org">NHibernate</a> ORM</li>
<li><a href="http://sparkviewengine.codeplex.com/">Spark View Engine</a></li>
</ul>
<p>My plan is to convert <a href="http://outofeggs.com/">Out  of  Eggs</a> to ASP.NET MVC 2, then explore some of these other technologies for use within it and other projects I&#8217;m currently working on.</p>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2010/agile-zen-asp-net-mvc-2-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Out of Eggs, a web app built in ASP.NET MVC, jQuery &amp; jQuery UI</title>
		<link>http://philderksen.com/2009/out-of-eggs-asp-net-mvc-jquery-jquery-ui/</link>
		<comments>http://philderksen.com/2009/out-of-eggs-asp-net-mvc-jquery-jquery-ui/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 22:26:55 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[fresno dev]]></category>

		<guid isPermaLink="false">http://philderksen.com/?p=188</guid>
		<description><![CDATA[I'm excited to announce outofeggs.com, a web app I've been working on for a while. It's built on the techniques I've gone through in my Categorized Item List series (using ASP.NET MVC, jQuery &#038; jQuery UI). Just create a list and see for yourself. The back end is SQL Server 2008.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m excited to announce <a href="http://outofeggs.com">outofeggs.com</a>, a web app I&#8217;ve been working on for a while. It&#8217;s built on the techniques I&#8217;ve gone through in my <a href="/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/">Categorized Item List series</a> (using ASP.NET MVC, jQuery &amp; jQuery UI). Just create a list and see for yourself. The back end is SQL Server 2008.</p>
<p>It probably goes without saying that I could use any and all feedback: bugs that pop up, features you&#8217;d like to see, usability issues, etc. Also let me know if there&#8217;s any development-related aspects of the app you&#8217;d like me to share in a post that I haven&#8217;t covered yet.</p>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/out-of-eggs-asp-net-mvc-jquery-jquery-ui/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Drag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 4</title>
		<link>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-4/</link>
		<comments>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-4/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 16:15:20 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://philderksen.com/?p=175</guid>
		<description><![CDATA[In this post I’ll go through the controller classes and how to use jQuery and AJAX to update the database with the position (or state) of where each section and item is moved to.

Every section can be dragged and dropped into any of the 4 columns and in any position within that column. This is the reason for both the ColumnNum and SortOrder fields of the Sections table described in part 2.

First we’ll dive into jQuery. Going back to our sortable() call for the sections, we need to add code that fires after an update event. The important thing to note here is that the update event will fire for both the column moving from and to. If moving within the same column, it’ll fire only once.]]></description>
			<content:encoded><![CDATA[<h3>Controllers and AJAX</h3>
<p>This is part 4 of a <a href="/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/">series</a>. In this post I’ll go through the controller classes and how to use jQuery and AJAX to update the database with the position (or state) of where each section and item is moved to.</p>
<p>Every section can be dragged and dropped into any of the 4 columns and in any position within that column. This is the reason for both the ColumnNum and SortOrder fields of the Sections table described in <a href="/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-2/">part 2</a>.</p>
<p>First we’ll dive into jQuery. Going back to our sortable() call for the sections, we need to add code that fires after an update event. The important thing to note here is that the update event will fire for both the column moving from and to. If moving within the same column, it’ll fire only once.</p>
<p>As set up in <a href="/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-3/">part 3</a>, the column num is stored in the id attribute of the “listColumn” div, so with a little parsing we can retrieve the column who’s state just changed.</p>
<p>Next we’ll need the new order of the sections within each changed column. The sortable(“serialize”) call forms the section IDs into a “form/ajax submittable string” like this:</p>
<p>section[]=3&amp;section[]=1&amp;section[]=4</p>
<p>For more detail see the <a href="http://jqueryui.com/demos/sortable">jQuery UI sortable</a> page. Look under Methods &gt; serialize.</p>
<p>Now we’ll do an AJAX post to a method within the section controller we’ll create below. Here’s the resulting jQuery:</p>
<pre class="brush: js;">function InitSectionSorting()
{
    $(".listColumn").sortable(
    {
        …,
        //update event fires both for column leaving and receiving
        update: function(event, ui)
        {
            //Extract column num from current div id
            var colNum = $(this).attr("id").replace(/col_/, "");

            $.post("/Section/UpdateSortOrder",
            { columnNum: colNum, sectionIdQueryString: $(this).sortable("serialize") });
        }
    });
}</pre>
<p>In SectionController.cs, we’ll now code the UpdateSortOrder method to receive the serialized string from jQuery and pass it as a string array to it’s model class.</p>
<pre class="brush: csharp;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateSortOrder(int columnNum, string sectionIdQueryString)
{
    string[] separator = new string[2] { "section[]=", "&amp;" };
    string[] sectionIdArray = sectionIdQueryString.Split(separator, StringSplitOptions.RemoveEmptyEntries);

    secRepo.UpdateSortOrder(columnNum, sectionIdArray);
    secRepo.Save();

    return Content("Success");
}</pre>
<p>The return Content(“Success”) is simply to see that the update was successful using <a href="http://getfirebug.com/">Firebug</a>. You should see the text “Success” within Firebug’s Console tab after you drag and drop a section. It’s optional so you can remove it.</p>
<p>Now on to Items. They can be moved to any section and in any position, so the jQuery and controller code is almost the same Sections.</p>
<p>jQuery:</p>
<pre class="brush: js;">function InitItemSorting()
{
    $(".itemList").sortable(
    {
        ...,
        //update event fires both for item list leaving and receiving
        update: function(event, ui)
        {
            //Extract section id from parent section box
            var sectionId = $(this).closest(".secBox").attr("id").replace(/section_/, "");

            $.post("/Item/UpdateSortOrder",
                { sectionId: sectionId, itemIdQueryString: $(this).sortable("serialize") });
        }
    });
}</pre>
<p>ItemController.cs:</p>
<pre class="brush: csharp;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateSortOrder(long sectionId, string itemIdQueryString)
{
    string[] separator = new string[2] { "item[]=", "&amp;" };
    string[] itemIdArray = itemIdQueryString.Split(separator, StringSplitOptions.RemoveEmptyEntries);

    itemRepo.UpdateSortOrder(sectionId, itemIdArray);
    itemRepo.Save();

    return Content("Success");
}</pre>
<p>In a later series we’ll cover editing the text of (and deleting) sections and items.</p>
<div class="woo-sc-box download   "><a href="http://philderksen.com/wp-content/uploads/2009/10/2009-10-08_CategorizedItemsListDemo.zip">Download the source code</a> (requires Visual Studio 2008 and ASP.NET MVC 1.0)</div>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-4/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Drag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 3</title>
		<link>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-3/</link>
		<comments>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-3/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 17:50:49 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://philderksen.com/?p=145</guid>
		<description><![CDATA[In this post I'll go through each of the Views (and the List controller). We already have the three repository classes in the Models folder. Now we need to add three controller classes to the Controllers folder: ListController.cs, SectionController.cs (for categories) and ItemController.cs.]]></description>
			<content:encoded><![CDATA[<h3>Views and Partial Views</h3>
<p>This is part 3 of a <a href="/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/">series</a>. In this post I&#8217;ll go through each of the Views (and the List controller). In part 4 I’ll go through the controller classes and how to use jQuery and AJAX to update the database.</p>
<p>We already have the three repository classes in the Models folder. Now we need to add three controller classes to the Controllers folder: ListController.cs, SectionController.cs (for categories) and ItemController.cs.</p>
<p>Next we’ll create a proper View for individual list records. For now we’ll continue to use the single hardcoded list record, so we’ll redirect from the Home controller/Index action to the List controller/Details action with the ID of 1. The List controller code is simply:</p>
<pre class="brush: csharp;">using CategorizedItemsListDemo.Models;

namespace CategorizedItemsListDemo.Controllers
{
    public class ListController : Controller
    {
        private ListRepository listRepo = new ListRepository();

        public ActionResult Details(long id)
        {
            List singleList = listRepo.GetById(id);
            return View(singleList);
        }
    }
}</pre>
<p>For now we don’t need to code up anything in the Section and Item controller classes, so we’ll move on to the views. The parent view we’ll use is the List/Details view. Since we’ll be looping through to add child Section records to the List record, and child Item records to each Section record, we’ll create two “partial views” (one for individual sections, one for individual items). This way user interface markup can be encapsulated without being repetitive (remember DRY – don’t repeat yourself).</p>
<p>Coming from an ASP.NET WebForms background, I equate partial views to the MVC way of doing user controls. They in fact use the same .ascx extension. I also added them to the /Views/Shared folder so the MVC engine can easily locate them. To sum it up, here are the three views added and the containing code:</p>
<p><strong>/Views/List/Details.aspx</strong></p>
<pre class="brush: csharp;">&lt;% for (int i = 1; i &lt;= 4; i++) { %&gt;
    &lt;div class="grid_3 listColumn" id="col_&lt;% =i %&gt;"&gt;
        &lt;% foreach (Section sec in Model.Sections.Where(s =&gt; s.ColumnNum == i).OrderBy(s =&gt; s.SortOrder)) { %&gt;
            &lt;% Html.RenderPartial("SingleSection", sec); %&gt;
        &lt;% } %&gt;
    &lt;/div&gt;
&lt;% } %&gt;</pre>
<p>Here the outside loop is simply going through each of the four columns setting the id attribute to the record id for use in jQuery. The inner loop is going through each Section in the List record (referenced by “Model” since the view is bound to the List model class). It simply uses a Lambda expression to render the Sections in the correct columns in the correct order. Then it passes off each individual Section to the SingleSection partial view.</p>
<p><strong>/Views/Shared/SingleSection.ascx</strong></p>
<pre class="brush: csharp;">&lt;div class="secBox" id="section_&lt;%= Model.SectionId %&gt;"&gt;
    &lt;div class="secHeader"&gt;
        &lt;h2 class="secName"&gt;&lt;%= Html.Encode(Model.SectionName) %&gt;&lt;/h2&gt;
    &lt;/div&gt;

    &lt;div class="itemBox"&gt;
        &lt;ul class="itemList"&gt;
            &lt;% foreach (Item item in Model.Items.OrderBy(i =&gt; i.SortOrder)) { %&gt;
                &lt;% Html.RenderPartial("SingleItem", item); %&gt;
            &lt;% } %&gt;
        &lt;/ul&gt;
    &lt;/div&gt;
&lt;/div&gt;</pre>
<p>Here we’re basically applying the same format from the List view to the Section partial view. Each Section is surrounded by a div with the id attribute set to the record id. “Model” is now bound to the Section model class, which we then use to display the Section name and loop through child Item records. We display Items in the correct sort order using a Lambda expression, then pass off each Item record to another partial view.</p>
<p><strong>/Views/Shared/SingleItem.ascx</strong></p>
<pre class="brush: csharp;">&lt;li class="itemRow" id="item_&lt;%= Model.ItemId %&gt;"&gt;
    &lt;span class="itemName"&gt;&lt;%= Html.Encode(Model.ItemName) %&gt;&lt;/span&gt;
&lt;/li&gt;</pre>
<p><span style="font-family: verdana;"> </span></p>
<p><span style="font-family: verdana;">This partial view is the simplest (for now). Again the id attribute is set to the record id. After that we simply render the item name.</span></p>
<p>That’s it. Now the app is rendering real data using MVC views. Nothing is hardcoded. To get things looking like they did in the initial layout, I populated the SQL database with sample data.</p>
<div class="woo-sc-box download   "><a href="http://philderksen.com/wp-content/uploads/2009/09/2009-09-02_CategorizedItemsListDemo.zip">Download the source code</a> (requires Visual Studio 2008 and ASP.NET MVC 1.0)</div>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Drag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 2</title>
		<link>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-2/</link>
		<comments>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-2/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 18:45:33 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://philderksen.com/?p=108</guid>
		<description><![CDATA[In this part I’ll describe the database structure and create the model classes needed for basic database interaction. To keep things simple, I went with a SQL Server 2005 Express database as it’s free and easy to create within Visual Studio 2008.]]></description>
			<content:encoded><![CDATA[<h3>Database and Model Classes</h3>
<p>This is part two of a <a href="/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/">series</a>. In this part I’ll describe the database structure and create the model classes needed for basic database interaction.</p>
<p>To keep things simple, I went with a SQL Server 2005 Express database as it’s free and easy to create within Visual Studio 2008. To create one, simply right-click on the App_Data folder and select SQL Server database. I named mine ListDemo.mdf.</p>
<p>After the database has been created, double-click on the new .mdf file to open it up. I created three tables: Lists, Sections and Items. Here’s the final database structure:</p>
<p><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="2009-07-15_db_diagram" src="http://philderksen.com/wp-content/uploads/2009/07/20090715_db_diagram1.png" border="0" alt="20090715 db diagram1" width="352" height="616" /></p>
<p>Make sure to set the keys and relationships appropriately. The first ID field of each table should be the primary key and set to auto-increment. I also recommend turning on cascade delete to make deleting whole sections or lists easier. I’ll get into tying the lists table to a users table later.</p>
<p>In the Sections table, the ColumnNum field is to indicate which of the four DIV columns each section resides in. Values must be between 1 and 4. Once narrowed down to a column, sections are sorted by their SortOrder value. Likewise, in the Items table items are sorted within sections by their SortOrder value.</p>
<p>For now I manually created one record in the List table and named it “Demo List 1”.</p>
<p><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="2009-07-15_list_table" src="http://philderksen.com/wp-content/uploads/2009/07/20090715_list_table.png" border="0" alt="20090715 list table" width="249" height="91" /></p>
<p>On to the “M” (models) in MVC. Again to keep it simple and quick, I chose to use <a href="http://msdn.microsoft.com/en-us/library/bb386976%28loband%29.aspx">LINQ to SQL</a> even though you could argue I should use <a href="http://msdn.microsoft.com/en-us/library/bb386964%28loband%29.aspx">LINQ to Entities</a>. I added a “LINQ to SQL Classes” item to the Models folder and named it ListDemo.dbml to match the database file. At this point the LINQ to SQL designer should pop open. Just drag the Sections, Lists and Items tables from the database view in the Server Explorer to the designer. When you click Save the LINQ to SQL code is generated for you behind behind the scenes. To view it look at the code-behind file for ListDemo.dbml.</p>
<p>Following a simple MVC convention, I created a model class for each table with the name ending in “Repository.” Specifically, ListRepository.cs, SectionRepository.cs and ItemRepository.cs (saved to the Models folder). Declared at the top of each class is a variable that references the data context. In each of the three classes I needed a method to retrieve a single record by ID. I called this GetById and used the <a href="http://msdn.microsoft.com/en-us/library/bb397947%28loband%29.aspx">Lambda/Method syntax</a> of LINQ. It’s virtually the same in all three classes, but here’s the code for SectionRepository.cs:</p>
<pre class="brush: csharp;">public class SectionRepository
{
    private ListDemoDataContext db = new ListDemoDataContext();

    public Section GetById(long id)
    {
        return db.Sections.Single(s =&gt; s.SectionId == id);
    }
}</pre>
<p>For now I’m going to ignore the ListRepository class since I’m just dealing with the single List record for now. In the Section and Item classes, next I coded up the Insert, Delete and Save methods. In all 3 methods I’m referencing the DataContext object, which has the already generated InsertOnSubmit(), DeleteOnSubmit() and SubmitChanges() methods (among others) in the LINQ to SQL auto-generated code. Here’s the code in SectionRepository.cs, but again it’s very similar in ItemRepository.cs:</p>
<pre class="brush: csharp;">public void Insert(Section sec)
{
    sec.SortOrder = GetNextSectionSortOrderValueByListIdColumnNum(sec.ListId, sec.ColumnNum);
    db.Sections.InsertOnSubmit(sec);
}

public void Delete(Section sec)
{
    //Items deleted via SQL cascade delete
    db.Sections.DeleteOnSubmit(sec);
}

public void Save()
{
    db.SubmitChanges();
}</pre>
<p>When a Section or Item record is inserted, it needs to have a SortOrder value that is one higher than the max SortOrder value that already exists within it’s group (all items within a section, or all sections within a column). Using LINQ I created a private method in each of these two classes to retrieve this value before saving the record. In SectionRepository.cs:</p>
<pre class="brush: csharp;">private int GetNextSectionSortOrderValueByListIdColumnNum(long listId, int colNum)
{
    //Max value is null if no items yet
    int? highestSortValue = (from s in db.Sections
                             where (s.ListId == listId) &amp;&amp; (s.ColumnNum == colNum)
                             select (int?)s.SortOrder).Max();

    return (highestSortValue ?? 0) + 1;
}</pre>
<p>When we drag sections or items around, we are basically re-ordering the SortOrder value (and possibly changing the ColumnNum value for sections). jQuery can pass a string of separated ID values when posting to the server via AJAX, so I created the method UpdateSortOrder with a ColumnNum (for Sections) or SectionId (for Items) parameter along with a string array parameter in the two repositories. In SectionRepository.cs:</p>
<pre class="brush: csharp;">public void UpdateSortOrder(int columnNum, string[] sectionIds)
{
    for (int i = 0; i &lt; sectionIds.Length; i++)
    {
        Section section = GetById(long.Parse(sectionIds[i]));
        section.ColumnNum = columnNum;
        section.SortOrder = i + 1;
    }
}</pre>
<p>To see the final code for all three repository classes, download the sample project at the end of this post.</p>
<p>I know there’s no UI updates in this part of the series, but it’s important to get the database and model classes established before moving on.</p>
<div class="woo-sc-box download   "><a href="http://philderksen.com/wp-content/uploads/2009/07/2009-07-17_CategorizedItemsListDemo.zip">Download the source code</a> (requires Visual Studio 2008 and ASP.NET MVC 1.0)</div>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Drag and Drop Categorized Item List with jQuery and ASP.NET MVC – Part 1</title>
		<link>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-1/</link>
		<comments>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-1/#comments</comments>
		<pubDate>Thu, 18 Jun 2009 22:35:51 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.philderksen.com/?p=76</guid>
		<description><![CDATA[There are plenty of to-do lists out there where you can drag and drop to sort individual items, but I wanted to take it a step further and introduce categories. I wanted the categories containing the items to be sortable themselves, and not just within one column but several so it would maximize use of the web page layout’s width. The main use case I had in mind was for a grocery list, where type of food would be the categories. But it could be used for other things like a movie collection (genres as categories) or a sports league player roster (team names as categories).]]></description>
			<content:encoded><![CDATA[<h3>Initial Layout and jQuery Setup</h3>
<p>There are plenty of to-do lists out there where you can drag and drop to sort individual items, but I wanted to take it a step further and introduce categories. I wanted the categories containing the items to be sortable themselves, and not just within one column but several so it would maximize use of the web page layout’s width. The main use case I had in mind was for a grocery list, where type of food would be the categories. But it could be used for other things like a movie collection (genres as categories) or a sports league player roster (team names as categories).</p>
<p>This is part one in a <a href="/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/">series</a>. In this post I’ll go through the initial layout and jQuery setup. In future posts I’ll go through the ASP.NET MVC setup in detail along with the database interaction.</p>
<p>For starters I kicked off an ASP.NET MVC project in Visual Studio 2008. I wanted a simple 4-column layout, so I added the CSS files from the excellent <a href="http://960.gs/">960 Grid System</a> and cleared out the existing Site.css file.</p>
<p>I’m using both jQuery and <a href="http://jqueryui.com/demos/sortable/">jQuery UI’s Sortable</a> functionality, both of which can be referenced on <a href="http://code.google.com/apis/ajaxlibs/">Google’s CDN</a> to reduce the page load time. I also added a new javascript file in the Scripts folder for custom functions.</p>
<p>With all these references the &lt;head&gt; section of the master page (/Views/Shared/Site.Master) now looks like this:</p>
<pre class="brush: csharp;">&lt;head runat="server"&gt;
    &lt;title&gt;&lt;asp:ContentPlaceHolder ID="TitleContent" runat="server" /&gt;&lt;/title&gt;

    &lt;link href="../../Content/reset.css" rel="stylesheet" type="text/css" /&gt;
    &lt;link href="../../Content/text.css" rel="stylesheet" type="text/css" /&gt;
    &lt;link href="../../Content/960.css" rel="stylesheet" type="text/css" /&gt;
    &lt;link href="../../Content/Site.css" rel="stylesheet" type="text/css" /&gt;

    &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script src="../../Scripts/Custom.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;/head&gt;</pre>
<p>Since we’re not going to delve into the ASP.NET MVC project structure for now, I created a new View simply called “Main” in the /Views/Shared folder, which in turn references the master page. This will contain all the content HTML for the time being. Before I started this blog post I called the categories <strong>sections</strong>, so bear with me on the terminology switch from here on out.</p>
<p>Using the 960 Grid System’s structure I laid out the 4 columns. For now I just added placeholders for two sections in the first column, and one section each under the 2nd and 4th columns. Here’s the layout in Main.aspx so far:</p>
<pre class="brush: csharp;">&lt;div class="container_12"&gt;

    &lt;div class="clear"&gt;&lt;/div&gt;

    &lt;div class="grid_12" id="headerText"&gt;
        &lt;h4&gt;Categorized List Demo&lt;/h4&gt;
    &lt;/div&gt;

    &lt;div class="clear"&gt;&lt;/div&gt;

    &lt;div class="grid_3 listColumn" id="col_1"&gt;
        &lt;div class="secBox"&gt;
            &lt;div class="secHeader"&gt;
                &lt;h2 class="secName"&gt;Vegetables&lt;/h2&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="secBox"&gt;
            &lt;div class="secHeader"&gt;
                &lt;h2 class="secName"&gt;Fruit&lt;/h2&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="grid_3 listColumn" id="col_2"&gt;
        &lt;div class="secBox"&gt;
            &lt;div class="secHeader"&gt;
                &lt;h2 class="secName"&gt;Meat&lt;/h2&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="grid_3 listColumn" id="col_3"&gt;
    &lt;/div&gt;

    &lt;div class="grid_3 listColumn" id="col_4"&gt;
        &lt;div class="secBox"&gt;
            &lt;div class="secHeader"&gt;
                &lt;h2 class="secName"&gt;Dairy&lt;/h2&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="clear"&gt;&lt;/div&gt;

&lt;/div&gt;</pre>
<p>Within each section I added 3 items in an unordered list. Each section now follows this pattern:</p>
<pre class="brush: csharp;">&lt;div class="secBox"&gt;
    &lt;div class="secHeader"&gt;
        &lt;h2 class="secName"&gt;Vegetables&lt;/h2&gt;
    &lt;/div&gt;

    &lt;div class="itemBox"&gt;
        &lt;ul class="itemList"&gt;
            &lt;li class="itemRow"&gt;
                &lt;span class="itemName"&gt;Broccoli&lt;/span&gt;
            &lt;/li&gt;
            &lt;li class="itemRow"&gt;
                &lt;span class="itemName"&gt;Spinach&lt;/span&gt;
            &lt;/li&gt;
            &lt;li class="itemRow"&gt;
                &lt;span class="itemName"&gt;Zuchinni&lt;/span&gt;
            &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/div&gt;
&lt;/div&gt;</pre>
<p>CSS markup was added for simple styling. Here’s a screenshot:</p>
<p><a href="http://philderksen.com/wp-content/uploads/2009/06/20090618-initial-layout.png" target="_blank" rel="lightbox[76]"><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="2009-06-18_initial_layout" src="http://philderksen.com/wp-content/uploads/2009/06/20090618-initial-layout-thumb.png" border="0" alt="20090618 initial layout thumb" width="640" height="160" /></a></p>
<p>To make sure the root of the site brings up the view “Main”, go to /Controllers/HomeController.cs and make sure the Index action returns this view.</p>
<pre class="brush: csharp;">public ActionResult Index()
{
    return View("Main");
}</pre>
<p>Next up is coding the javascript to enable drag and drop on both the sections and items. When making the sortable() call, sections must use the connectWith attribute to link to the 4 different columns, and items must use the same attribute to link to different sections.</p>
<p>For sections, I also set a handle so the user is forced to use the header to drag the sections around. If this isn’t included, there would be a conflict when dragging items since they already exist within the sections. Dragging a section by it’s header is also common among popular personalized home page sites such as <a href="http://www.google.com/ig">iGoogle</a> and <a href="http://www.pageflakes.com/">PageFlakes</a>. Other than that there are just some visual attributes set (cursor, opacity, placeholder) along with containment so the user can’t scroll off the page dragging things around. Here’s the javascript so far:</p>
<pre class="brush: js;">$(document).ready(function()
{
    InitSectionSorting();
    InitItemSorting();
});

function InitSectionSorting()
{
    $(".listColumn").sortable(
    {
        connectWith: ".listColumn",
        containment: "document",
        cursor: "move",
        handle: ".secHeader",
        opacity: 0.8,
        placeholder: "secBoxPlaceholder"
    });
}

function InitItemSorting()
{
    $(".itemList").sortable(
    {
        connectWith: ".itemList",
        containment: "document",
        cursor: "move",
        opacity: 0.8,
        placeholder: "itemRowPlaceholder"
    });
}</pre>
<p>Here’s what it looks like dragging a section:</p>
<p><img style="display: inline; border-width: 0px;" title="2009-06-18_section_drag" src="http://philderksen.com/wp-content/uploads/2009/06/20090618-section-drag.png" border="0" alt="20090618 section drag" width="262" height="125" /></p>
<p>…and an item:</p>
<p><img style="display: inline; border-width: 0px;" title="2009-06-18_item_drag" src="http://philderksen.com/wp-content/uploads/2009/06/20090618-item-drag.png" border="0" alt="20090618 item drag" width="235" height="95" /></p>
<p>That’s about it for the layout and sorting functionality. In future posts I’ll tackle adding, editing and deleting using jQuery’s AJAX calling ASP.NET MVC methods, which in turn access a SQL Server database.</p>
<p>Final note: The styling seems to get messed up in IE. Should look OK in FF, Chrome and Safari though.</p>
<div class="woo-sc-box download   "><a href="/wp-content/uploads/2009/06/2009-06-18_categorizeditemslistdemo.zip">Download the source code</a> (requires Visual Studio 2008 and ASP.NET MVC 1.0)</div>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-1/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Series for Drag and Drop Categorized Item List with jQuery and ASP.NET MVC</title>
		<link>http://philderksen.com/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/</link>
		<comments>http://philderksen.com/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 23:14:18 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://philderksen.com/2009/09/01/series-for-drag-and-drop-categorized-item-list-with-jquery-and-asp-net-mvc/</guid>
		<description><![CDATA[A table of contents for my series on building a drag and drop categorized item list app with jQuery and ASP.NET MVC.]]></description>
			<content:encoded><![CDATA[<p>A table of contents for my series on building a drag and drop categorized item list app with jQuery and ASP.NET MVC.</p>
<ul>
<li><a href="/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-1/">Part 1: Initial Layout and jQuery Setup</a></li>
<li><a href="/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-2/">Part 2: Database and Model Classes</a></li>
<li><a href="/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-3/">Part 3: Views and Partial Views</a></li>
<li><a href="/2009/drag-and-drop-categorized-item-list-jquery-asp-net-mvc-part-4/">Part 4: Controllers and AJAX</a></li>
<li><a href="/2009/out-of-eggs-asp-net-mvc-jquery-jquery-ui/">Out of Eggs, a web app built in ASP.NET MVC, jQuery &amp; jQuery UI</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/series-drag-and-drop-categorized-item-list-jquery-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the PBworks API with ASP.NET MVC and jQuery</title>
		<link>http://philderksen.com/2009/pbworks-api-with-aspnet-mvc-and-jquery/</link>
		<comments>http://philderksen.com/2009/pbworks-api-with-aspnet-mvc-and-jquery/#comments</comments>
		<pubDate>Thu, 14 May 2009 00:25:23 +0000</pubDate>
		<dc:creator>Phil Derksen</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PBworks]]></category>

		<guid isPermaLink="false">http://philderksen.nfshost.com/?p=22</guid>
		<description><![CDATA[Recently my company went with PBworks (formerly PBwiki) to use for internal collaboration. One of my projects is building a “dashboard” web app to bring in data from different sources, and the first thing users want to see in it is the recent activity log from the wiki. Here’s how I tapped into the PBworks API and brought it into the web app, which is being built using ASP.NET MVC and jQuery.]]></description>
			<content:encoded><![CDATA[<p>Recently my company went with <a href="http://pbworks.com/">PBworks</a> (formerly PBwiki) to use for internal collaboration. One of my projects is building a &#8220;dashboard&#8221; web app to bring in data from different sources, and the first thing users want to see in it is the recent activity log from the wiki. Here&#8217;s how I tapped into the PBworks API and brought it into the web app, which is being built using <a href="http://www.asp.net/mvc/">ASP.NET MVC</a> and <a href="http://jquery.com/">jQuery</a>.</p>
<p>Since I can’t display my company data, I created a demo project using the <a href="http://jqueryui.pbworks.com/">jQuery UI design &amp; planning wiki</a> (a great resource in itself), since it&#8217;s a public wiki. The jQuery UI wiki is already enabled for API use. If you want to enable your own wiki, go to Settings &gt; Developer Interface. Also note your three API keys as they’ll need to be passed along depending on your security settings.</p>
<p>Looking through the <a href="http://pbworks.com/api_v2/">PBworks API documentation</a> you’ll notice that they return all data in <a href="http://en.wikipedia.org/wiki/JSON">JSON</a>. Naturally I thought the quickest route to retrieving that data would be call it’s URLs directly using jQuery’s <a href="http://docs.jquery.com/Ajax/jQuery.getJSON">getJSON</a> call.</p>
<p>In my ASP.NET MVC project, for now I just wanted to see the PBworks data on the default view. So I simply went to /Views/Home/Index.aspx, cleared out the default content and added a custom div tag. The plan was to populate the div tag via AJAX using jQuery. Later this might make sense to move to a PartialView.</p>
<p>Directly after the div tag I added javascript to fill the div with the data returned from the PBworks API call. In this case I’ll use the <a href="http://pbworks.com/api_v2/#GetChanges">GetChanges</a> call to start and do a test to see if the getJSON call even executes. Here’s the code for the MainContent section of the view:</p>
<pre class="brush: csharp;">&lt;div id="pbWorksData"&gt;
&lt;/div&gt;

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

    $(document).ready(function() {
        $.getJSON("http://jqueryui.pbworks.com/api_v2/op/GetChanges/_type/jsontext", function(data)
        {
            $("#pbWorksData").append("data goes here");
        });
    });

&lt;/script&gt;</pre>
<p>Since we’re using jQuery we need to add a reference to it in the main head tag. I added mine to the master page at /Views/Shared/Site.master.</p>
<pre class="brush: csharp;">&lt;script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"&gt;&lt;/script&gt;</pre>
<p>Unfortunately this first attempt didn’t work, which confused me for a while. The same type of call works with the Flickr API using the sample code in the jQuery <a href="http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback">getJSON</a> docs. The URL also works if you <a href="http://jqueryui.pbworks.com/api_v2/op/GetChanges/_type/jsontext">navigate to it straight</a>. And for this public wikis you don’t need to pass any API keys in the URL.</p>
<p>Further inspection with the excellent <a href="http://getfirebug.com/">Firebug</a> add-on reveals a security error.</p>
<p><a href="http://philderksen.com/wp-content/uploads/20090512-jsonsecurityerror.png" rel="lightbox[22]"><img class="size-full wp-image-59 alignnone" title="20090512-jsonsecurityerror.png" src="http://philderksen.com/wp-content/uploads/20090512-jsonsecurityerror.png" alt="20090512 jsonsecurityerror" width="521" height="232" /></a></p>
<p>Turns out the PBworks folks aren’t allowing cross-domain javascript calls, even using <a href="http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">JSONP</a> which is supported in jQuery as of version 1.2. This was confirmed in an email to them, reasons being for security. Notice also we’re not passing in a</p>
<p>To get around the cross-domain issue, we’ll just access the API via server-side code in a model class using the WebRequest and WebResponse classes. In fact we’ll just pass the JSON straight to the controller with little modification.</p>
<p>Here’s the complete PBworks model class. Notice at the end we had to strip out some surrounding text <strong>(/* -secure- */</strong>). If you don’t do this it won’t be recognized as JSON. PBworks informed me that it was in there to prevent the hijacking of credentials over browsers, and that they’re working on an alternative method to remove the need for this extra text.</p>
<pre class="brush: csharp;">using System.IO;
using System.Net;

namespace PbApiDemo.Models
{
    public class PBworks
    {
        public string GetChanges()
        {
            string url = "http://jqueryui.pbworks.com/api_v2/op/GetChanges/_type/jsontext";

            WebRequest request = HttpWebRequest.Create(url);
            WebResponse response = request.GetResponse();
            string jsonResponse = "";

            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
            }

            //Strip out surrounding /* -secure- */ text to keep it recognized as JSON
            jsonResponse = jsonResponse.Replace("/*-secure-", "");
            jsonResponse = jsonResponse.Replace("*/", "");

            return jsonResponse;
        }
    }
}</pre>
<p>In the controller class (PBworksController), I just created an instance of the PBworks model and passed the JSON through as text, setting the browser’s page type to application/json.</p>
<pre class="brush: csharp;">using System.Web.Mvc;
using PbApiDemo.Models;

namespace PbApiDemo.Controllers
{
    public class PBworksController : Controller
    {
        private PBworks pbw = new PBworks();

        public ActionResult GetChanges()
        {
            return Content(pbw.GetChanges(), "application/json");
        }
    }
}</pre>
<p>Now that the correct JSON is returned from a controller in the project, back in our default view we just change the URL in the javascript code.</p>
<pre class="brush: csharp;">$(document).ready(function() {
    $.getJSON("/PBworks/GetChanges", function(data)
    {
        $("#pbWorksData").append("data goes here");
    });
});</pre>
<p>Ran the project now and sure enough the test text inside the getJSON call shows up. Now we’re in business.</p>
<p>Now that I had the complete JSON object, I needed to iterate over each item returned and render them appropriately on the page. To quickly see what’s available I pasted the JSON into this cool <a href="http://json.bloople.net/">JSON 2 HTML</a> tool.</p>
<p>For use in jQuery, the parent object we’re concerned with is actually contained in the <strong>changes</strong> collection. From each item within <strong>changes</strong>, I wanted to display and link the page, author, action taken on that page, and show the lasted edited date/time. I appended all this html via jQuery doing some formatting and manipulation to get the links and date/times right. Later on we might want to move the javascript to another file and optimize it a bit, but it works for now. Here’s the final javascript contained in the default view:</p>
<pre class="brush: csharp;">&lt;script type="text/javascript"&gt;

    $(document).ready(function() {
        $.getJSON("/PBworks/GetChanges", function(data)
        {
            //Create an unordered list to hold all the entries
            $("#pbWorksData").append($("&lt;ul/&gt;"));

            $.each(data.changes, function(i, item)
            {
                if (item.page != null)
                {
                    //Get date/time from "epoch" number
                    var editDate = new Date(item.time * 1000);

                    $("#pbWorksData ul")
                        .append($("&lt;li/&gt;")
                            .append($("&lt;a/&gt;")
                                //Page name and link
                                //Replace spaces with dashes in url
                                .attr("href", "http://jqueryui.pbworks.com/" + item.page.replace(/ /g,"-"))
                                .append(item.page))
                            .append(" - ")
                            //Page "action"
                            .append(item.op_word)
                            .append(" by ")
                            .append($("&lt;a/&gt;")
                                //Page author and link
                                .attr("href", "http://jqueryui.pbworks.com/user/" + item.user_id)
                                .append(item.user_name))
                            .append(" on ")
                            //Last edited date
                            .append(editDate.toLocaleString())
                        );
                }
            });
        });
    });

&lt;/script&gt;</pre>
<p>The final rendering looks like this:</p>
<p><a href="http://philderksen.com/wp-content/uploads/20090513-blog-pbworks-api-1.png" rel="lightbox[22]"><img class="alignnone size-full wp-image-61" title="20090513-blog-pbworks-api-1.png" src="http://philderksen.com/wp-content/uploads/20090513-blog-pbworks-api-1.png" alt="20090513 blog pbworks api 1" width="585" height="268" /></a></p>
<p>Hopefully this helps anyone else out there working with the PBworks API.</p>
<div class="woo-sc-box download   "><a href="http://philderksen.com/wp-content/uploads/2009/05/2009-05-13_pbapidemo.zip">Download the demo project</a> (requires Visual Studio 2008 and ASP.NET MVC)</div>
]]></content:encoded>
			<wfw:commentRss>http://philderksen.com/2009/pbworks-api-with-aspnet-mvc-and-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

