<?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>Ivan Zlatev &#187; Coding</title>
	<atom:link href="http://ivanz.com/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://ivanz.com</link>
	<description></description>
	<lastBuildDate>Wed, 09 Jan 2013 16:17:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Guide for migrating an ASP.NET MVC Solution to .NET 4.5 and ASP.NET MVC 4</title>
		<link>http://ivanz.com/2012/08/20/guide-for-migrating-an-asp-net-mvc-solution-to-net-4-5-and-asp-net-mvc-4/</link>
		<comments>http://ivanz.com/2012/08/20/guide-for-migrating-an-asp-net-mvc-solution-to-net-4-5-and-asp-net-mvc-4/#comments</comments>
		<pubDate>Mon, 20 Aug 2012 20:08:37 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=981</guid>
		<description><![CDATA[<a href="http://ivanz.com/2012/08/20/guide-for-migrating-an-asp-net-mvc-solution-to-net-4-5-and-asp-net-mvc-4/" title="Guide for migrating an ASP.NET MVC Solution to .NET 4.5 and ASP.NET MVC 4"></a>You can find a very handy step by step guide for migrating to ASP.NET MVC 4 here . It might seem a bit long, but actually with a few multi-file search and replace and some regex you can do it pretty &#8230;<p class="read-more"><a href="http://ivanz.com/2012/08/20/guide-for-migrating-an-asp-net-mvc-solution-to-net-4-5-and-asp-net-mvc-4/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2012/08/20/guide-for-migrating-an-asp-net-mvc-solution-to-net-4-5-and-asp-net-mvc-4/" title="Guide for migrating an ASP.NET MVC Solution to .NET 4.5 and ASP.NET MVC 4"></a>			<content:encoded><![CDATA[<p>You can find a very handy step by step guide for migrating to ASP.NET MVC 4 <a href="http://www.asp.net/whitepapers/mvc4-release-notes#_Toc303253806">here</a> . It might seem a bit long, but actually with a few multi-file search and replace and some regex you can do it pretty quickly.</p>
<p>I just wanted to add a few more tips:</p>
<h4>Migrating to ASP.NET MVC 4</h4>
<p>If you are still using bin deployables (&#8220;Add Deployable Assembly&#8221;) for your current ASP.NET MVC setup &#8211; you should remove it and replace it with the <em>AspNetMvc</em> nuget package.</p>
<p>If you are using <em>MvcContrib</em> or <em>MvcFutures</em> &#8211; it&#8217;s probably best to update to<em> MvcContrib.Mvc3-ci </em>and <em>Mvc3Futures . </em>Either case you will have to deal with the clash of extension methods (<a href="http://msdn.microsoft.com/en-us/library/hh429726(v=vs.108)">Html.IdFor, Html.NameFor, etc</a>) which were previously in Mvc Futures (Microsoft.Web.Mvc.dll) but now are part of the core ASP.NET MVC assembly. Until updated versions of MvcContrib and MvcFutures come out I have resolved this by removing the  using statement from my View&#8217;s Web.config for the MvcFutures extensions methods namespace. This however means that you lose tiny things like Html.SubmitButton, which you can easily replace across the whole solution with html code using a Regex.</p>
<p>Be careful about underwater rocks like<a title="Heads up on a hidden breaking change in ASP.NET MVC 4" href="http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/"> this one about the new Date and DateTime editor templates in MVC 4</a>. Also there seem to be model binding changes to do with <em>DateTime</em> &#8211; so far that has been the major pain in the ass for me.</p>
<h4>Re-targeting for .NET 4.5</h4>
<p>The fastest way to convert all projects is by doing a search and replace across all *.csproj files and replace <em>&lt;TargetFrameworkVersion&gt;v4.0&lt;/TargetFrameworkVersion&gt;  </em>with<em> &lt;TargetFrameworkVersion&gt;v4.5&lt;/TargetFrameworkVersion&gt; </em>(or client profile, etc)</p>
<p>also replace in your Web.config <em>compilation</em> element <em>targetFramework=&#8221;4.0&#8243;</em> with 4.5</p>
<p>The real issue are the NuGet packages &#8211; some have a .NET 4.5 specific version &#8211; a good example is Entity Framework. When the project is targeting version 4.0 of the framework and you install/update EF to version 5 you actually end up with EF 4.4 (which doesn&#8217;t have support for enums and so on). The only way to solve this is to remove all packages and install them again, which is a massive pain to do manually and unfortunately the current version of NuGet is not of much help there either, but the daily build is. <a href="http://stackoverflow.com/questions/12006991/retargeting-solution-from-net-4-0-to-4-5-how-to-retarget-the-nuget-packages">More details about retargeting the NuGet packages are available in this StackOverflow question.</a></p>
<h4>A few other notes</h4>
<p>Things that I have personally tested and work fine: MiniProfiler works fine with an runtime assembly binding redirect for Entity Framework, ELMAH and Ninject work without any changes. Noticed a small regression in unobtrusive validation and checkboxed when pulling a form with AJAX, but I that ended caused by a jQuery Validation problem.</p>
<p>Oh and by the way, don&#8217;t forget to update your test assemblies <em>App.config </em>with the correct assembly redirects if you are running tests against ASP.NET MVC controllers, which use MvcFutures or MvcContrib, because you will end up seeing weird &#8220;Type A doesn&#8217;t match type A&#8221; errors.</p>
<p>To be honest I haven&#8217;t seen noticeable performance improvements with the MVC 4 + .NET 4.5 + EF5 combo so far, but time will tell.</p>
 <img src="http://ivanz.com/?feed-stats-post-id=981" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2012/08/20/guide-for-migrating-an-asp-net-mvc-solution-to-net-4-5-and-asp-net-mvc-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows 8 Code Weekend: 8-9th September in London &#8211; dev4good</title>
		<link>http://ivanz.com/2012/08/17/windows-8-code-weekend-8-9th-september-in-london-dev4good/</link>
		<comments>http://ivanz.com/2012/08/17/windows-8-code-weekend-8-9th-september-in-london-dev4good/#comments</comments>
		<pubDate>Fri, 17 Aug 2012 22:20:13 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[dev4good]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=976</guid>
		<description><![CDATA[<a href="http://ivanz.com/2012/08/17/windows-8-code-weekend-8-9th-september-in-london-dev4good/" title="Windows 8 Code Weekend: 8-9th September in London - dev4good"></a>TheGivingLab.Org We’re running a second dev4good event in collaboration with TheGivingLab.org and Givey this year to bring together talented thinkers, designers and coders from around the UK to work on some real-world issues faced by UK charities. The technology theme &#8230;<p class="read-more"><a href="http://ivanz.com/2012/08/17/windows-8-code-weekend-8-9th-september-in-london-dev4good/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2012/08/17/windows-8-code-weekend-8-9th-september-in-london-dev4good/" title="Windows 8 Code Weekend: 8-9th September in London - dev4good"></a>			<content:encoded><![CDATA[<div style="float: right;">
<p><img style="border: 1px solid black; margin-top: 10px; margin-bottom: 10px; float: right;" src="http://dev4good.net/Media/Default/Page/welcome-to-orchard/weneedmonkey.gif" alt="" width="200" height="166" /> <img style="clear: right; float: RIGHT;" src="http://dev4good.net/Media/Default/pdf/microsoft-logo.jpg" alt="" width="200" height="48" /><img style="clear: right; display: block; margin-left: auto; margin-right: auto;" src="http://www.seren.com/html/images/logo/seren_logo.png" alt="" width="126" height="33" /></p>
<div style="clear: right; display: block; margin-left: auto; margin-right: auto; text-align: center;"><span style="font-family: 'arial black', 'avant garde'; font-size: large;">TheGivingLab.Org</span></div>
</div>
<p>We’re running a second dev4good event in collaboration with TheGivingLab.org and Givey this year to bring together talented thinkers, designers and coders from around the UK to work on some real-world issues faced by UK charities. The technology theme for the event is <strong>Windows 8</strong>, but <span style="text-decoration: underline;"><strong>no prior knowledge</strong></span> of Windows 8 app development is required.</p>
<p>Microsoft will present <em>Windows 8 Developer Overview</em>, showing us the technical perspective. Seren will be next up talking about how to design a great experience on Windows 8. (Full details of these sessions will follow shortly.) TheGivingLab.org, will be sharing charity projects, apps and experiences they’d like inspire you with and sharing learnings from their first tech experiment www.seethedifference.org. We may even work on one of your own ideas – if you’ve got one.</p>
<p>Our goals for the weekend are simple. We want to learn how to create Windows 8 apps that could change the way people live their lives – and then we’re going to spend the rest of the time doing it!</p>
<div>
<p>If you are a software developer (on any platform), designer, computing student, or are just interested in help out – then we need you. It’s going to be a real challenge – and sleep will be optional. Are you up for it? If you are, the event page is <a href="http://www.dev4good.net/windows-8-code-weekend-2012">here</a>.</p>
<p>Remember, this is a not-for-profit event being run by volunteers, so you won’t be paid for the work you do. You will, however, get to meet and work with some of the smartest developers and designers in the UK – all while doing some real good for society.</p>
<p>We’re also looking for sponsorship for this event, so please <a href="http://dev4good.net/contact" target="_blank">contact us</a> if you believe you can help in any way.</p>
<p>If you are a UK charity or a community based organisation, then <a href="http://dev4good.net/bit-for-charity">have a look at what we could do for you</a> or <a href="http://dev4good.net/contact" target="_blank">contact us</a> directly. Thank you.</p>
<p>We need you help &#8211; so spread the word, <a href="http://www.dev4good.net/Media/Default/pdf/win_8_poster.pdf" target="_blank">download our poster</a> and put it up where you work, send it to your friends.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.dev4good.net/Media/Default/pdf/poster.jpg" alt="" width="442" height="624" /></p>
</div>
 <img src="http://ivanz.com/?feed-stats-post-id=976" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2012/08/17/windows-8-code-weekend-8-9th-september-in-london-dev4good/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Heads up on a hidden breaking change in ASP.NET MVC 4</title>
		<link>http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/</link>
		<comments>http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/#comments</comments>
		<pubDate>Fri, 17 Aug 2012 22:14:56 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=973</guid>
		<description><![CDATA[<a href="http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/" title="Heads up on a hidden breaking change in ASP.NET MVC 4"></a>If you, like me, are using an Editor Template for DateTime and use the DataTypeAttribute with either or DataType.Date and DataType.DateTime in ASP.NET MVC 2 or 3 and happen to upgrade to ASP.NET MVC 4 be aware! ASP.NET MVC 4 &#8230;<p class="read-more"><a href="http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/" title="Heads up on a hidden breaking change in ASP.NET MVC 4"></a>			<content:encoded><![CDATA[<p>If you, like me, are using an Editor Template for DateTime and use the <em>DataTypeAttribute</em> with either or <em>DataType.Date</em> and <em>DataType.DateTime</em> in ASP.NET MVC 2 or 3 and happen to upgrade to ASP.NET MVC 4 <strong>be aware!</strong></p>
<p>ASP.NET MVC 4 introduces two new internal editor templates for properties marked as <em>DataType.Date</em> and <em>DataType.DateTime </em>to render HTML5 input types (date and datetime accordingly).</p>
<p>The unexpected side-effect of this is that if you were previously capturing all <em>DateTime </em>type editing through a <em>DateTime</em> editor template now if your property is marked as <em>DataType.Date</em> ASP.NET MVC 4 will use the new internal <em>Date</em> editor template instead of your <em>DateTime </em>editor template.</p>
<p>The solution is to provide a <em>Date.cshtml </em>editor template along your<em> DateTime.cshtml</em> editor template.</p>
 <img src="http://ivanz.com/?feed-stats-post-id=973" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2012/08/17/heads-up-on-a-hidden-breaking-change-in-asp-net-mvc-4/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>dev4good &#8211; Developing for a Better World</title>
		<link>http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/</link>
		<comments>http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 22:44:59 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Diary]]></category>
		<category><![CDATA[Achievements]]></category>
		<category><![CDATA[Charity]]></category>
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=930</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/" title="dev4good - Developing for a Better World"></a>Last weekend (2-3 July) I attended the first ever dev4good &#8211; a charity hackathon where developers try to solve charity problems in a weekend. It took place in Hammersmith, London in a amazing venue on the riverside: Three charities came &#8230;<p class="read-more"><a href="http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/" title="dev4good - Developing for a Better World"></a>			<content:encoded><![CDATA[<p><a href="http://ivanz.com/wp-content/uploads/2011/07/charity-portal-screenshot.png" rel="shadowbox[sbpost-930];player=img;"><br />
</a>Last weekend (2-3 July) I attended the first ever <a href="http://dev4good.net">dev4good</a> &#8211; a charity hackathon where developers try to solve charity problems in a weekend. It took place in Hammersmith, London in a amazing venue on the riverside:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/07/IMG_1305.jpg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-945" title="IMG_1305" src="http://ivanz.com/wp-content/uploads/2011/07/IMG_1305-1024x764.jpg" alt="" width="620" height="462" /></a></p>
<p>Three charities came to use with the following problems:</p>
<p><a href="www.hopeandplay.org">Hope and Play</a> were looking for a way to locate and manage resources. And allow other charities or people to do the same.</p>
<p><a href="www.ministryofstories.org">The Ministry of Stories</a> were looking for a way to get more young people writing stories and publishing these to the world. All while helping to generate a little more cash along the way.</p>
<p><a href="www.craftanddesigncouncil.org.uk">The Design and Craft Council</a> want to be able to automate their awards processes.</p>
<p>We were about 25 people and were able to split in three teams. Here is a video of my team explaining what we are planning to achieve for the Hope and Play project (I am the one speaking first):</p>
<p><iframe width="620" height="465" src="http://www.youtube.com/embed/ml0nhtuA9Bo?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p>Basically we wanted to create a proof of concept system that:</p>
<ol id="internal-source-marker_0.27231994923204184">
<li>Provides a central web portal to aggregate information and also allow charities to communicate what projects they are running, and in which locations.</li>
<li>Allows charities to communicate in real-time work and achievements on their projects via the web portal, Twitter or mobile text messages (SMS).</li>
<li>Enable charities and individuals to advertise their available and required resources (human power, building material, etc) and its location.</li>
<li>Provides a means for charities to discover information on the web relevant to their projects and location.</li>
</ol>
<p>At the end it looked like this (test data, which probably doesn&#8217;t illustrate perfectly the usage):</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/07/charity-portal-screenshot.png" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter" title="charity portal screenshot" src="http://ivanz.com/wp-content/uploads/2011/07/charity-portal-screenshot.png" alt="" width="1003" height="841" /></a><br />
My team worked great together. We were able to quickly split the work so that everyone has something of interest to do. It was very exciting to see how we are making progress during our scrum stand ups:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/WP_000815.jpg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-950" title="WP_000815" src="http://ivanz.com/wp-content/uploads/2011/07/WP_000815-1024x768.jpg" alt="" width="620" height="465" /></a><br />
At the start of the event we decided that we are going to use Git for source control and GitHub for hosting. Apart from me only one other person had used Git before, but I was happy to help out each of the guys and keep them going during the event. As you can see from the below GitHub commits timeline we were quite effective in working in parallel:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/Weekend-Timeline.png" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-951" title="Weekend Timeline" src="http://ivanz.com/wp-content/uploads/2011/07/Weekend-Timeline-1024x105.png" alt="" width="620" height="63" /></a><br />
I think 99.9% of us were running Windows and using Bash or Cmd was absolutely not an option for the non-Gitters who had mainly experience with TFS or SVN. Most new Gitters used Tortoise Git, but that was still confusing as it required understanding of how everything works. Only later I learned about SmartGit and in retrospect I think we should have used that instead.</p>
<p>As you&#8217;ll hear on the video initially we planned to use Orchard CMS, but after some research and poking around I was personally disappointed to find out how over-complex and over-engineered Orchard is. So we dumped it and went for plain old ASP.NET MVC 3 and non-POCO Entity Framework, which worked out quite well &#8211; after all it was just meant to be proof of concept.</p>
<p>All in all I had great fun during the weekend. I also met some great people, who I am looking forward to seeing and work with again in the future &#8211; probably during GiveCamp UK in October!</p>
<p>At the end of the weekend it turned out that most people voted for me as the most supportive and helpful developer during the weekend, so I won the grand prize &#8211; a Kinect. I wasn&#8217;t expecting this at all and very grateful to everyone and very happy that I was able to help people out. Thanks guys!<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/Kinect-Prize.jpeg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-medium wp-image-953" title="Kinect Prize" src="http://ivanz.com/wp-content/uploads/2011/07/Kinect-Prize-300x224.jpg" alt="" width="300" height="224" /></a>And here is an end of event photo of team dev4good:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/WP_000825.jpg" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-large wp-image-954" title="WP_000825" src="http://ivanz.com/wp-content/uploads/2011/07/WP_000825-1024x768.jpg" alt="" width="620" height="465" /></a>Great job guys!</p>
<p>Also big thanks to our sponsors:<br />
<a href="http://ivanz.com/wp-content/uploads/2011/07/sponsors.png" rel="shadowbox[sbpost-930];player=img;"><img class="aligncenter size-medium wp-image-955" title="sponsors" src="http://ivanz.com/wp-content/uploads/2011/07/sponsors-300x179.png" alt="" width="300" height="179" /></a></p>
<h3>What&#8217;s next?</h3>
<p>We are in the process of moving and merging the team repositories in a central one in GitHub. I am looking forward to get in touch with some charities to discuss and get feedback for our proof of concept Charity Portal and its eventual real-life practical application.</p>
<p>Next also is GiveCamp UK! I am also tempted to go to Startup Weekend Lonodon, but I&#8217;ll see about that.</p>
 <img src="http://ivanz.com/?feed-stats-post-id=930" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/07/04/dev4good-developing-for-a-better-world/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Featured on the home page of ASP.NET</title>
		<link>http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/</link>
		<comments>http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 20:28:02 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Diary]]></category>
		<category><![CDATA[Achievements]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=931</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/" title="Featured on the home page of ASP.NET"></a>Really exciting for me is that a few days ago my series on Editing Variable Length Reorderable Collections in ASP.NET MVC got featured on the home page of the ASP.NET web site. I just wanted to say thank you to &#8230;<p class="read-more"><a href="http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/" title="Featured on the home page of ASP.NET"></a>			<content:encoded><![CDATA[<p>Really exciting for me is that a few days ago my series on <a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Editing Variable Length Reorderable Collections in ASP.NET MVC</a> got featured  on the home page of the ASP.NET web site. I just wanted to say thank you to the person who decided to share it with the community. Here is a screenshot:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/07/Ivan-Zlatev-ASP.NET-Home-Page.png" rel="shadowbox[sbpost-931];player=img;"><img src="http://ivanz.com/wp-content/uploads/2011/07/Ivan-Zlatev-ASP.NET-Home-Page.png" alt="" title="Ivan Zlatev ASP.NET Home Page" width="1157" height="1023" class="aligncenter size-full wp-image-932" /></a></p>
 <img src="http://ivanz.com/?feed-stats-post-id=931" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/07/03/featured-on-the-home-page-of-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Editing Variable Length Reorderable Collections in ASP.NET MVC &#8211; Part 3: Knockout JS</title>
		<link>http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/</link>
		<comments>http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 16:48:27 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[KnockoutJS]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=844</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 3: Knockout JS"></a>In Part 1 of this series I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation. In Part 2 of this series &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 3: Knockout JS"></a>			<content:encoded><![CDATA[<p><a title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 1" href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">In Part 1 of this series</a> I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation.</p>
<p><a title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2" href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">In Part 2 of this series</a> I began moving some aspects of the collection editing to the client-side with jQuery Templates, but we realized that it&#8217;s not good enough, because instead of dealing with data we are juggling with our ASP.NET MVC views generated HTML.</p>
<p>In this final Part 3 of the series I want to move the collection editing completely to the client-side using the <a href="http://knockoutjs.com/">Knockout JS library</a> JavaScript library. I will look at:</p>
<ul>
<li>Knockout JS data-binding and tempalting</li>
<li>JSON Form (data really &#8211; no form) submission</li>
<li>jQuery Client-Side Validation </li>
</ul>
<p>I will re-implement our sample collection editor and it is going to look exactly the same as it did before. Before I begin just a reminder that <a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing">all of the source code is available on GitHub as a Visual Studio solution</a>.</p>
<h4>What is Knockout JS?</h4>
<p>I am going to quote its creator (Steven Sanderson) from his introductory post, where he provides <a href="http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/">a very good overview</a>:</p>
<blockquote><p>Knockout is a JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using <em>observers </em>to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM pattern, offering <em>declarative bindings </em>somewhat like Silverlight but without the browser plugin.</p></blockquote>
<p>I suggest you read the above linked post or checkout the Knockout JS web site to learn more about it, but to quickly summarize how it works:</p>
<ul>
<li>A JavaScipt view model is defined that holds all the data. All the data properties are initialized as (or wrapped in) observable values and arrays.</li>
<li>HTML elements can be data-bound to a property (similar to WinForms/XAML(WPF/Silverlight)) from the view model using the <em>data-bind </em>attribute syntax. We can bind an input&#8217;s value, a span&#8217;s text, etc. to a view model property.</li>
<li>Whenever a value/or array changes the data-binding kicks in and the HTML element are automatically updated.</li>
<li>Knockout uses jQuery and supports templating via jQuery Templates.</li>
</ul>
<h4>Our Sample</h4>
<p>To understand this lets jump straight into our sample app.</p>
<p>I have added a third edit option to our sample:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit.png" rel="shadowbox[sbpost-844];player=img;"><img class="aligncenter size-full wp-image-856" title="knockout-edit" src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit.png" alt="" width="304" height="223" /></a></p>
<p>which surprise, surprise looks exactly the same as in the previous iteration. Apart from one extra feature &#8211; the favourite movies counter I&#8217;ve added to give you a hint of the power of Knockout JS:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-screen.png" rel="shadowbox[sbpost-844];player=img;"><img class="aligncenter size-full wp-image-857" title="knockout-edit-screen" src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-screen.png" alt="" width="571" height="383" /></a></p>
<h4>View and ViewModel</h4>
<p>Let&#8217;s firstly look at the first iteration of our view model implementation:</p>
<pre class="brush: xml; title: ; notranslate">&lt;script type=&quot;text/javascript&quot;&gt;
var viewModel = {
    Id: ko.observable(@Model.Id),
    Name: ko.observable(&quot;@Model.Name&quot;),
    FavouriteMovies: ko.observableArray(@Html.Json(@Model.FavouriteMovies) || []),

    maxMovies: 10,
    
    addMovie: function() {
        viewModel.FavouriteMovies.push(@Html.Json(new Movie()));
    },

    removeMovie: function(movie) {
        ko.utils.arrayRemoveItem(viewModel.FavouriteMovies, movie);
    }
};

$(function () {
    ko.applyBindings(viewModel);
});
&lt;/script&gt;</pre>
<p>We:</p>
<ul>
<li>Serialize our ASP.NET MVC <em>User</em> Model to JSON (<em>Id</em>, <em>Name</em>, <em>FavouriteMovies</em>). <em>Html.Json</em> is a custom Html helper that simply wraps a JSON serializer &#8211; you can <a href="https://github.com/ivanz/ASP.NET-MVC-Collection-Editing/blob/master/CollectionEditing/Infrastructure/JsonHtmlExtensions.cs">see it in the source code</a>.</li>
<li>Wrap its values in Knockout observables and then once the page is loaded we initialize Knockout JS with our model</li>
<li>Define some add/remove movie methods to edit the FavouriteMovies collection</li>
</ul>
<p><strong>What&#8217;s crucial here is that we are not dealing with nor manipulating HTML markup</strong>, which is something that we were doing heavily in the previous parts.</p>
<p>When processed server-side the above view model will look like roughly like this in the browser:</p>
<pre class="brush: xml; title: ; notranslate">var viewModel = {
        Id: ko.observable(1),
        Name: ko.observable(&quot;Ivan Zlatev&quot;),
        FavouriteMovies: ko.observableArray([{&quot;Title&quot;:&quot;Movie 1&quot;,&quot;Rating&quot;:5},
                                                           {&quot;Title&quot;:&quot;Movie 2&quot;,&quot;Rating&quot;:10},
                                                           {&quot;Title&quot;:&quot;Movie 3&quot;,&quot;Rating&quot;:12}] || []),

        maxMovies: 10,

        addMovie: function() {
            viewModel.FavouriteMovies.push({&quot;Title&quot;:null,&quot;Rating&quot;:0});
        },

        removeMovie: function(movie) {
            ko.utils.arrayRemoveItem(viewModel.FavouriteMovies, movie);
        }
}</pre>
<p>Let&#8217;s look at the first iteration of our edit view (<em>EditKnockoutJS.cshtml</em>) to better understand how does Knockout help us:</p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.User
@{ ViewBag.Title = &quot;Edit My Account With Knockout JS&quot;; }

&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery.validate.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jQuery.tmpl.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/knockout-1.2.1.debug.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/knockout.jQueryUI-sortable.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;h2&gt;Edit&lt;/h2&gt;

@using (Html.BeginForm(&quot;EditKnockoutJS&quot;, &quot;User&quot;, FormMethod.Post, new { id = &quot;profileEditorForm&quot; })) {
    @Html.ValidationSummary(false)
    &lt;fieldset&gt;
        &lt;legend&gt;My Details&lt;/legend&gt;

        &lt;input name=&quot;userId&quot; type=&quot;hidden&quot; data-bind=&quot;value: Id&quot;/&gt;

        &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;
        &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; data-bind=&quot;value: Name&quot; /&gt;
    &lt;/fieldset&gt;
    
    &lt;fieldset&gt;
        &lt;legend&gt;My Favourite Movies&lt;/legend&gt;

        &lt;ul id=&quot;moviesEditor&quot; style=&quot;list-style-type: none&quot;
            data-bind=&quot;template: { name: 'moviesTemplate', data: FavouriteMovies }, 
                       sortableList: viewModel.FavouriteMovies&quot; &gt;
        &lt;/ul&gt;
        &lt;p&gt;You have &lt;span data-bind=&quot;text: FavouriteMovies().length&quot;&gt;&lt;/span&gt; favourite movies.&lt;/p&gt;

        &lt;script id=&quot;moviesTemplate&quot; type=&quot;text/x-jquery-template&quot;&gt;
            {{each(i, movie) $data}}
                &lt;li data-bind=&quot;sortableItem: movie&quot;&gt;
                    &lt;div data-bind=&quot;template: { name: 'movieTemplate', data: movie }&quot;&gt;&lt;/div&gt;
                &lt;/li&gt;
            {{/each}}
        &lt;/script&gt;

        &lt;script id=&quot;movieTemplate&quot; type=&quot;text/x-jquery-template&quot;&gt;
            &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

            &lt;label&gt;Title:&lt;/label&gt;
            &lt;input type=&quot;text&quot; data-bind=&quot;value: Title&quot;/&gt;

            &lt;label&gt;Rating:&lt;/label&gt;
            &lt;input type=&quot;text&quot; data-bind=&quot;value: Rating&quot;/&gt;

            &lt;a href=&quot;#&quot; data-bind=&quot;click: function() { viewModel.removeMovie(this); }&quot;&gt;Delete&lt;/a&gt;
        &lt;/script&gt;
    
        &lt;button data-bind=&quot;click: addMovie, enable: FavouriteMovies().length &lt; maxMovies&quot;&gt;Add another&lt;/button&gt;
    &lt;/fieldset&gt;

    &lt;p&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
        &lt;a href=&quot;/&quot;&gt;Cancel&lt;/a&gt;
    &lt;/p&gt;
}</pre>
<p>In our view we use Knockout JS to data-bind our HTML input fields to the data in the viewModel (notice the &#8220;<em>data-bind</em>&#8221; attributes).</p>
<p>For the collection editor:</p>
<ul>
<li>Similar to Part 2, we have a movie jQuery template, which defines the HTML fields of a movie, but this time we don&#8217;t use any ASP.NET MVC helpers.</li>
<li>We make the HTML list reorderable via Drag and Drop with the two special <em>sortableList</em> and <em>sortableItem</em> bindings.This is a custom Knockout JS binding I&#8217;ve created and hosted on <a href="https://github.com/ivanz/knockout.jQueryUI-sortable.js/blob/master/knockout.jQueryUI-sortable.js">GitHub here</a>. Behind the scenes it magically creates a JQuery UI Sortable keeps our <em>viewModel.FavouriteMovies</em> collection in sync when the widget changes.</li>
<li>We limit the number of favourite movies a user can add via the &#8220;Add Another&#8221; button to ten by using a &#8220;<em>enabled</em>&#8221; binding with a boolean expression. Behind the scenes Knockout JS will manage the state of the button and toggle between enabled/disabled depending on the evaluated value of the expression.</li>
<li>Finally we data-bind a <em>span</em> element to display the current number of favourite movies the user has added. Again, this is something that Knockout will keep up to date for us.</li>
</ul>
<p>Right now with this viewModel and that view we have a working drag and drop add/remove favourite movies editor. What we are still missing however is:</p>
<ul>
<li>Form submission and server-side handling</li>
<li>Form validation</li>
</ul>
<h4>Form Submission and Handling</h4>
<p>Let&#8217;s add some more code to our view model and view to handle form submission.</p>
<p>Firstly we are going to implement a save function in our view model. Because we are no longer using ASP.NET model views, we can&#8217;t simply submit the form as is &#8211; the &#8220;standard&#8221; form values based ASP.NET MVC model binding won&#8217;t work properly and especially so for the collection editing part. </p>
<p>Thankfully starting from version 3 ASP.NET MVC supports out of the box JSON model binding. It kicks in if the HTTP request Content-Type is set to &#8220;application/json&#8221;. So instead of using form submission we are going to post our view model data via an AJAX post request to our MVC action, containing the data in JSON serialized form:</p>
<pre class="brush: jscript; title: ; notranslate"> var viewModel = {
       ... snip ...

        saveFailed: ko.observable(false),

        // Returns true if successful
        save: function()
        {
            var saveSuccess = false;
            viewModel.saveFailed(false);

            // Executed synchronously for simplicity
            jQuery.ajax({
                type: &quot;POST&quot;,
                url: &quot;@Url.Action(&quot;EditKnockoutJS&quot;, &quot;User&quot;)&quot;,
                data: ko.toJSON(viewModel),
                dataType: &quot;json&quot;,
                contentType: &quot;application/json&quot;,
                success: function(returnedData) {
                    saveSuccess = returnedData.Success || false;
                    viewModel.saveFailed(!saveSuccess);
                },
                async: false
            });

            return saveSuccess;
        }
};</pre>
<p>Then we will suppress the default form submission behaviour and replace it with our own:</p>
<pre class="brush: xml; title: ; notranslate">&lt;p&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Save&quot; 
             data-bind=&quot;click: function() { viewModel.save(); return false; }&quot;/&gt;
    &lt;a href=&quot;/&quot;&gt;Cancel&lt;/a&gt;
&lt;/p&gt;
    
&lt;p data-bind=&quot;visible: saveFailed&quot; class=&quot;error&quot;&gt;A problem occurred saving the data.&lt;/p&gt;</pre>
<p>Note that I have added a new &#8220;<em>saveFailed</em>&#8221; property in the viewModel which is set by <em>save()</em>. I have also used a &#8220;<em>visible</em>&#8221; data binding on the value of that property to display the error message paragraph only if the save operation has failed.</p>
<p>Now let&#8217;s also look at the MVC action to handle the form submission:</p>
<pre class="brush: csharp; title: ; notranslate">
[HttpPost]
public ActionResult EditKnockoutJS(User user)
{
    FormResponseData responseData = new FormResponseData() {
        Success = false
    };

    if (this.ModelState.IsValid) {
        CurrentUser = user;
        responseData.Success = true;
    }

    return Json(responseData);
}

class FormResponseData {
    public bool Success { get; set; }
}</pre>
<p>Pretty simple action, which just validates the Model using our validation rules/data annotations and returns a <em>FormReponseData</em> object serialized to JSON, which contains a Success flag expected by the client side.</p>
<p>We can now persist our view model and also use our server-side model validation to prevent the client from doing nasty things:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-server-validation.png" rel="shadowbox[sbpost-844];player=img;"><img src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-server-validation.png" alt="" title="knockout-edit-server-validation" width="558" height="207" class="aligncenter size-full wp-image-905" /></a></p>
<p>We are not done just yet. Because we no longer use the ASP.NET html helpers we no longer pull the server-side validation error messages and are currently left with the generic &#8220;Something went wrong.&#8221; error message. This isn&#8217;t exactly nice nor user friendly. We can solve this by the use of client-side JavaScript based validation. Remember that we should never ever rely solely on the client-side (and we don&#8217;t in our case).</p>
<h4>Client-Side Validation</h4>
<p>Unfortunately at the time of writing I couldn&#8217;t find anything that validates against the Knockout JS viewModel instead of the HTML markup, so I had to resort to <a href="http://docs.jquery.com/Plugins/validation">jQuery Validation</a> for the client-side validation. The problem with that is that we need to ensure that we have set proper unique &#8220;name&#8221; attributes on our form fields and especially so for our collection editor elements.</p>
<p>Fortunately Knockout JS already has a binding for that called the &#8220;<em>uniqueName</em> binding&#8221;, so all we have to do is add that to our favourite movie collection editor fields like I&#8217;ve showed below and don&#8217;t worry about generating them ourselves. This is great, because as you saw in Part 2 injecting a unique name during jQuery template evaluation is relatively tricky.</p>
<pre class="brush: xml; title: ; notranslate">&lt;script id=&quot;movieTemplate&quot; type=&quot;text/x-jquery-template&quot;&gt;
    &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

    &lt;label&gt;Title:&lt;/label&gt;
    &lt;input type=&quot;text&quot; data-bind=&quot;value: Title, uniqueName: true&quot; class=&quot;required&quot;/&gt;

    &lt;label&gt;Rating:&lt;/label&gt;
    &lt;input type=&quot;text&quot; data-bind=&quot;value: Rating, uniqueName: true&quot; class=&quot;required&quot;/&gt;

    &lt;a href=&quot;#&quot; data-bind=&quot;click: function() { viewModel.removeMovie(this); }&quot;&gt;Delete&lt;/a&gt;
&lt;/script&gt;</pre>
<p>There are multiple ways we can use jQuery Validation and I have decided to go for the simplest declarative one, where we decorate our fields with extra attributes to describe the value constraints that we want to enforce. Let&#8217;s update the above fields to make the <em>Title</em> and <em>Rating</em> required:</p>
<pre class="brush: xml; title: ; notranslate">&lt;label&gt;Title:&lt;/label&gt;
&lt;input type=&quot;text&quot; data-bind=&quot;value: Title, uniqueName: true&quot; class=&quot;required&quot;/&gt;

&lt;label&gt;Rating:&lt;/label&gt;
&lt;input type=&quot;text&quot; data-bind=&quot;value: Rating, uniqueName: true&quot; class=&quot;required&quot;/&gt;</pre>
<p>Finally let&#8217;s plug-in jQuery Validation. To do that we will remove the previous submit button handler and use jQuery Validation instead:</p>
<pre class="brush: xml; title: ; notranslate">
... snip... 

        &lt;input type=&quot;submit&quot; value=&quot;Save&quot;/&gt;

... snip... 

&lt;script type=&quot;text/javascript&quot;&gt;
    $(function () {
        ko.applyBindings(viewModel);

        $(&quot;#profileEditorForm&quot;).validate({
            submitHandler: function(form) {
                if(viewModel.save())
                    window.location.href = &quot;/&quot;;

                return false;
            }
        });
    });
&lt;/script&gt;</pre>
<p>Which gives us nice per-field validation error messages as we type:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-client-validation.png" rel="shadowbox[sbpost-844];player=img;"><img src="http://ivanz.com/wp-content/uploads/2011/06/knockout-edit-client-validation.png" alt="" title="knockout-edit-client-validation" width="676" height="276" class="aligncenter size-full wp-image-909" /></a></p>
<h4>Wrapping up</h4>
<p><a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing">Download all of the source code from GitHub as a Visual Studio solution.</a></p>
<p>In this part we looked at Knockout JS and how great it is in terms of helping us avoid manipulation of HTML markup among many other things. This is generally something that can get really messy quickly and become hard to maintain and track. We also looked at how it helps us neatly solve our collection editing problem without having to worry about practically anything. In the expense of the sacrifice of our Html helpers and partial views, etc we get a lot of flexibility on the client side to add more interactivity in a neat and clean way.</p>
<h4>Final Words</h4>
<p>If you have a simple collection editing scenario and you are heavily reliant on your ASP.NET MVC views, partial views, editors and displays the approach documented in <a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Part 1</a> should be sufficient. And if pulling in new entries/rows via AJAX is not an option (e.g. for speed, performance or any other reasons) you can pull in <a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">Part 2</a>. However IMHO the better solution most of the time is to use Knockout JS and what I have described in this part as it opens the doors for more complex client-side interactions in a neat and clean way.</p>
<p>Thank you for reading the series. I will appreciate your feedback in the comments!</p>
 <img src="http://ivanz.com/?feed-stats-post-id=844" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Custom Knockout JS binding for jQuery UI Sortable</title>
		<link>http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/</link>
		<comments>http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 20:23:24 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[KnockoutJS]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=865</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/" title="Custom Knockout JS binding for jQuery UI Sortable"></a>For the work in progress Part 3 of my Editing Variable Length Reorderable Collections in ASP.NET MVC blog series I have created a custom Knockout JS binding that keeps a Knockout JS observable array in sync with a jQuery UI &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/" title="Custom Knockout JS binding for jQuery UI Sortable"></a>			<content:encoded><![CDATA[<p>For the work in progress Part 3 of my <a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Editing Variable Length Reorderable Collections in ASP.NET MVC</a> blog series I have created a custom Knockout JS binding that keeps a Knockout JS observable array in sync with a jQuery UI sortable.</p>
<p>It&#8217;s available here:</p>
<p>Basic usage is to use a <em>sortableList</em> binding on the <em>ul</em> which you  want to make a jQuery Sortable and then a <em>sortableItem</em> binding for each sortable item (<em>li</em>) in the list like that: </p>
<pre class="brush: xml; title: ; notranslate">&lt;ul data-bind=&quot;sortableList: yourObservableArray&quot; &gt; 
    {{each(i, arrayItem) yourObservableArray}} 
        &lt;li data-bind=&quot;sortableItem: arrayItem&quot;&gt;&lt;/li&gt; 
    {{/each}} 
&lt;/ul&gt;</pre>
<p>Live example (if you are reading this in a feed reader you will need to open the blog post properly to see this):</p>

<!-- iframe plugin v.2.6 wordpress.org/extend/plugins/iframe/ -->
<iframe src="http://ivanz.github.com/knockout.jQueryUI-sortable.js/example.html" width="100%" height="400" scrolling="no" class="iframe-class" frameborder="0"></iframe>
 <img src="http://ivanz.com/?feed-stats-post-id=865" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/27/custom-knockout-js-binding-for-jquery-ui-sortable/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates</title>
		<link>http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/</link>
		<comments>http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/#comments</comments>
		<pubDate>Mon, 20 Jun 2011 19:21:44 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=796</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates"></a>In Part 1 of this series I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation. And while the solution provided in Part &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates"></a>			<content:encoded><![CDATA[<p><a title="Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 1" href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">In Part 1 of this series</a> I discussed the problems that we face when implementing an editor for a variable length, reorderable collection and reuse our server-side ASP.NET MVC views, model binding and validation. And while the solution provided in Part 1 is nice and clean (and I personally use it in a few projects) one field for improvement in true Agile Blogging fashion is to find a way to remove the AJAX request we use for fetching new editor rows.</p>
<p>One way to bring this completely to the client side is by the use of <a href="http://api.jquery.com/category/plugins/templates/">jQuery Template</a> (or any other JavaScript templating engine/library).</p>
<p>A reminder of what our editor looks like before I begin and a second remind that the source code is available on <a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing">GitHub</a>:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image3.png" rel="shadowbox[sbpost-796];player=img;"><img class="size-full wp-image-780 aligncenter" title="Sample Editor" src="http://ivanz.com/wp-content/uploads/2011/06/image3.png" alt="" width="550" height="435" /></a></p>
<p>To start with I have added a second link to our sample&#8217;s home page titled &#8220;Edit with jQuery templates&#8221;:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/home-jquery.png" rel="shadowbox[sbpost-796];player=img;"><img class="aligncenter size-full wp-image-803" title="Home Page of the sample" src="http://ivanz.com/wp-content/uploads/2011/06/home-jquery.png" alt="" width="298" height="202" /></a></p>
<p>Corresponding controller actions:</p>
<pre class="brush: csharp; title: ; notranslate">
public ActionResult EditJQueryTemplate()
{
    return View(CurrentUser);
}

[HttpPost]
public ActionResult EditJQueryTemplate(User user)
{
    if (!this.ModelState.IsValid)
        return View(user);

    CurrentUser = user;
    return RedirectToAction(&quot;Display&quot;);
}</pre>
<p>And a new editor view (<em>EditJQueryTemplate.cshtml</em>) which is exactly the same as the one from Part 1 apart from the core editor bit:</p>
<pre class="brush: xml; highlight: [16,26]; title: ; notranslate">&lt;legend&gt;My Favourite Movies&lt;/legend&gt;

@if (Model.FavouriteMovies == null || Model.FavouriteMovies.Count == 0) {
    &lt;p&gt;None.&lt;/p&gt;
}
&lt;ul id=&quot;moviesEditor&quot; style=&quot;list-style-type: none&quot;&gt;
    @if (Model.FavouriteMovies != null) {
        foreach (Movie movie in Model.FavouriteMovies) {
            Html.RenderPartial(&quot;MovieEntryEditor&quot;, movie);
        }
    }
&lt;/ul&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/jQuery.tmpl.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/x-jquery-tmpl&quot; id=&quot;movieTemplate&quot;&gt;
    @Html.CollectionItemJQueryTemplate(&quot;MovieEntryEditor&quot;, new Movie())
&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    $(function () {
        $(&quot;#moviesEditor&quot;).sortable();
    });

    var viewModel = {
        addNew: function () {
            $(&quot;#moviesEditor&quot;).append($(&quot;#movieTemplate&quot;).tmpl({ index: viewModel._generateGuid() }));
        },

        _generateGuid: function () {
            // Source: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r &amp; 0x3 | 0x8);
                return v.toString(16);
            });
        }
    };
&lt;/script&gt;
            
&lt;a id=&quot;addAnother&quot; href=&quot;#&quot; onclick=&quot;viewModel.addNew();&quot;&gt;Add another&lt;/a&gt;</pre>
<p>Note the new <em>@Html.CollectionItemJQueryTemplate</em> helper, which takes a collection item instance with default values and the unchanged partial view <em>MovieEntryEditor</em> from Part 1:</p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.Movie
           
&lt;li style=&quot;padding-bottom:15px&quot;&gt;
    @using (Html.BeginCollectionItem(&quot;FavouriteMovies&quot;)) {
        &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

        @Html.LabelFor(model =&gt; model.Title)
        @Html.EditorFor(model =&gt; model.Title)
        @Html.ValidationMessageFor(model =&gt; model.Title)

        @Html.LabelFor(model =&gt; model.Rating)
        @Html.EditorFor(model =&gt; model.Rating)
        @Html.ValidationMessageFor(model =&gt; model.Rating)

        &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
    }
&lt;/li&gt;
</pre>
<p>Basically the helper renders the partial with an ${$index} jQuery template placeholder for which we supply a GUID at run-time on the client-side when we render the template. The output of the helper looks like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;script type=&quot;text/x-jquery-tmpl&quot; id=&quot;movieTemplate&quot;&gt;
&lt;li style=&quot;padding-bottom:15px&quot;&gt;

    &lt;input autocomplete=&quot;off&quot; name=&quot;FavouriteMovies.Index&quot; type=&quot;hidden&quot; value=&quot;${index}&quot; /&gt;

    &lt;img src=&quot;/Content/images/draggable-icon.png&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

    &lt;label&gt;Title&lt;/label&gt;
    &lt;input name=&quot;FavouriteMovies[${index}].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;

    &lt;label&gt;Rating&lt;/label&gt;
    &lt;input name=&quot;FavouriteMovies[${index}].Rating&quot; type=&quot;text&quot; value=&quot;0&quot; /&gt;

    &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
&lt;/li&gt;
&lt;/script&gt;</pre>
<p>Everytime the &#8220;Add another&#8221; button is pressed this template is rendered using a new GUID index value supplied by the <em>viewModel</em> class.</p>
<p>Here is the code of the <em>@Html.CollectionItemJQueryTemplate</em> helper:</p>
<pre class="brush: csharp; title: ; notranslate">public static MvcHtmlString CollectionItemJQueryTemplate&lt;TModel, TCollectionItem&gt;(this HtmlHelper&lt;TModel&gt; html, 
                                                                                    string partialViewName, 
                                                                                    TCollectionItem modelDefaultValues)
{
    ViewDataDictionary&lt;TCollectionItem&gt; viewData = new ViewDataDictionary&lt;TCollectionItem&gt;(modelDefaultValues);
    viewData.Add(JQueryTemplatingEnabledKey, true);
    return html.Partial(partialViewName, modelDefaultValues, viewData);
}</pre>
<p>It renders the supplied partial view, but before that it sets a flag on the ViewContext&#8217;s ViewData dictionary to indicate that the view is to be rendered as jQuery collection item template. This is then handled by the <em>@Html.BeginCollectionItem</em> by generating an index template placeholder based .Index hidden field for model binding instead of one with an actual GUID value:</p>
<pre class="brush: csharp; title: ; notranslate">public static IDisposable BeginCollectionItem&lt;TModel&gt;(this HtmlHelper&lt;TModel&gt; html, string collectionName)
{
    string collectionIndexFieldName = String.Format(&quot;{0}.Index&quot;, collectionName);

    string itemIndex = null;
    if (html.ViewData.ContainsKey(JQueryTemplatingEnabledKey)) {
        itemIndex = &quot;${index}&quot;;
    } else {
        itemIndex = GetCollectionItemIndex(collectionIndexFieldName);
    }

    string collectionItemName = String.Format(&quot;{0}[{1}]&quot;, collectionName, itemIndex);

    TagBuilder indexField = new TagBuilder(&quot;input&quot;);
    indexField.MergeAttributes(new Dictionary&lt;string, string&gt;() {
        { &quot;name&quot;, collectionIndexFieldName },
        { &quot;value&quot;, itemIndex },
        { &quot;type&quot;, &quot;hidden&quot; },
        { &quot;autocomplete&quot;, &quot;off&quot; }
    });
// snip---</pre>
<p>That&#8217;s it! We are still reusing our ASP.NET views, model binding and validation, but no longer require an AJAX request to fetch a new editor row!.</p>
<p>In Part 3 I will look at Knockout JS templating, data binding and moving variable length reorderable collection editing completely on the client side with the MVVM pattern and using JavaScript form serialization and JSON data submission and model binding.</p>
<p><strong>Next: <a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/">Part 3 and Knockout JS client-side collection editing, JSON model binding and client-side validation.</a></strong></p>
 <img src="http://ivanz.com/?feed-stats-post-id=796" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Editing Variable Length Reorderable Collections in ASP.NET MVC &#8211; Part 1: ASP.NET MVC Views</title>
		<link>http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/</link>
		<comments>http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 19:46:37 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=786</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 1: ASP.NET MVC Views"></a>Introduction I have decided to write a short series of blog posts on editing collections and more specifically variable length collections in ASP.NET MVC. I will take two different implementation approaches: In Part 1 I look at implementing collection editing &#8230;<p class="read-more"><a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/" title="Editing Variable Length Reorderable Collections in ASP.NET MVC - Part 1: ASP.NET MVC Views"></a>			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>I have decided to write a short series of blog posts on editing collections and more specifically variable length collections in ASP.NET MVC. I will take two different implementation approaches:</p>
<ol>
<li><a href="http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/">In <strong>Part 1</strong></a> I look at implementing collection editing by sticking to facilities provided to us by ASP.NET MVC such as views, partial views, editor templates, model binding, model validation, etc.</li>
<li><a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">In <strong>Part 2</strong></a> I further enhance the sample by using jQuery Templates, but still utilize the same ASP.NET MVC views from Part 1.</li>
<li><a href="http://ivanz.com/2011/06/29/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-3/">In <strong>Part 3</strong></a> I will look at Knockout JS templating, data binding and moving variable length reorderable collection editing completely on the client side with the MVVM pattern and  JSON data submission and model binding.</li>
</ol>
<p>The aspects I will consider are:</p>
<ul>
<li>Dynamically adding, removing and reordering items to/from the collection</li>
<li>Validation implications</li>
<li>Code Reusability and Refactoring implications</li>
</ul>
<p>I will assume that you are already familiar with ASP.NET MVC and basic JavaScript concepts.</p>
<h3>Source Code</h3>
<p><a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing" target="_blank">All source code is available on GitHub</a></p>
<h3>The Sample</h3>
<p>What I am going to build is a little sample where we have a user who has a list of favourite movies. It will look roughly like on the image below and will allow for adding new favourite movies, removing favourite movies and also reordering them up and down using the drag handler.</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image3.png" rel="shadowbox[sbpost-786];player=img;"><img style="background-image: none; margin: 10px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; padding-top: 0px; border-width: 0px;" title="image" src="http://ivanz.com/wp-content/uploads/2011/06/image_thumb3.png" border="0" alt="image" width="554" height="439" /></a></p>
<h3>Domain Model</h3>
<p>The domain model is basically:</p>
<p>
<pre class="brush: csharp; title: ; notranslate">public class User
{
    public int? Id { get; set; }
    [Required]
    public string Name { get; set; }
    public IList&lt;Movie&gt; FavouriteMovies { get; set; }
}</pre>
</p>
<p>and</p>
<p>
<pre class="brush: csharp; title: ; notranslate">public class Movie
{
    [Required]
    public string Title { get; set; }
    public int Rating { get; set; }
}</pre>
</p>
<p>Let’s get cracking!</p>
<h3>An Edit View</h3>
<p>Let’s start by creating a first-pass edit view for our Person to look like the one on the image above:</p>
<p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.User
@{ ViewBag.Title = &quot;Edit My Account&quot;; }

&lt;h2&gt;Edit&lt;/h2&gt;

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    &lt;fieldset&gt;
        &lt;legend&gt;My Details&lt;/legend&gt;

        @Html.HiddenFor(model =&gt; model.Id)

        &lt;div class=&quot;editor-label&quot;&gt;
            @Html.LabelFor(model =&gt; model.Name)
        &lt;/div&gt;
        &lt;div class=&quot;editor-field&quot;&gt;
            @Html.EditorFor(model =&gt; model.Name)
            @Html.ValidationMessageFor(model =&gt; model.Name)
        &lt;/div&gt;
    &lt;/fieldset&gt;
    
    &lt;fieldset&gt;
        &lt;legend&gt;My Favourite Movies&lt;/legend&gt;

        @if (Model.FavouriteMovies == null || Model.FavouriteMovies.Count == 0) {
            &lt;p&gt;None.&lt;/p&gt;
        } else {
            &lt;ul id=&quot;movieEditor&quot; style=&quot;list-style-type: none&quot;&gt;
                @for (int i=0; i &lt; Model.FavouriteMovies.Count; i++) {
                    &lt;li style=&quot;padding-bottom:15px&quot;&gt;
                        &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

                        @Html.LabelFor(model =&gt; model.FavouriteMovies[i].Title)
                        @Html.EditorFor(model =&gt; model.FavouriteMovies[i].Title)
                        @Html.ValidationMessageFor(model =&gt; model.FavouriteMovies[i].Title)

                        @Html.LabelFor(model =&gt; model.FavouriteMovies[i].Rating)
                        @Html.EditorFor(model =&gt; model.FavouriteMovies[i].Rating)
                        @Html.ValidationMessageFor(model =&gt; model.FavouriteMovies[i].Rating)

                        &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
                    &lt;/li&gt;
                }
            &lt;/ul&gt;
            &lt;a href=&quot;#&quot;&gt;Add another&lt;/a&gt;
        }

        &lt;script type=&quot;text/javascript&quot;&gt;
            $(function () {
                $(&quot;#movieEditor&quot;).sortable();
            });
        &lt;/script&gt;
    &lt;/fieldset&gt;
    
    &lt;p&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
        &lt;a href=&quot;/&quot;&gt;Cancel&lt;/a&gt;
    &lt;/p&gt;
}</pre>
</p>
<p>The view is creating a list of editing controls for each of the movies in <em>Person.FavouriteMovies</em>. I am using a jQuery selector and dom function to remove a movie when the user clicks “Delete”  and also a <a href="http://jqueryui.com/demos/sortable/" target="_blank">jQuery UI Sortable</a> to make the items from the HTML list drag and droppable up and down.</p>
<p>With this done we immediately face the first problem: <span style="text-decoration: underline;">We haven’t implemented the “Add another”</span>. Before we do that let’s consider how ASP.NET MVC model binding of collections works.</p>
<h3>ASP.NET MVC Collection Model Binding Patterns</h3>
<p>There are two patterns for model binding collections in ASP.NET MVC. The <strong>first one</strong> you have just seen:</p>
<p>
<pre class="brush: xml; title: ; notranslate">@for (int i=0; i &lt; Model.FavouriteMovies.Count; i++) {
    @Html.LabelFor(model =&gt; model.FavouriteMovies[i].Title)
    @Html.EditorFor(model =&gt; model.FavouriteMovies[i].Title)
    @Html.ValidationMessageFor(model =&gt; model.FavouriteMovies[i].Title)
…
}</pre>
</p>
<p>which generates similar HTML:</p>
<pre class="brush: xml; title: ; notranslate">&lt;label for=&quot;FavouriteMovies_0__Title&quot;&gt;Title&lt;/label&gt;
&lt;input id=&quot;FavouriteMovies_0__Title&quot; name=&quot;FavouriteMovies[0].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;span class=&quot;field-validation-error&quot;&gt;The Title field is required.&lt;/span&gt;</pre>
</p>
<p>This is really great for displaying collections and editing static length collections, but problematic when we want to edit variable length collections, because:</p>
<ol>
<li><strong>Indices have to be sequential (0, 1, 2, 3, …). If they aren’t ASP.NET MVC stops at the first gap. E.g. if you have item 0, 1, 3, 4 after the model binding has finished you will end up with a collection of two items only – 1 and 2 instead of four items.</strong></li>
<li><strong>If you were to reorder the list in the HTML ASP.NET MVC will apply the indices order not the fields order when doing model binding.</strong></li>
</ol>
<p>This basically means that add/remove/reorder scenarios are no go with this. It’s not impossible but it will be big big mess tracking add/remove/reorder actions and re-indexing all field attributes.</p>
<p>Now, someone might say – “<em>Hey, why don’t you just implement a non-sequential collection model binder?”</em> .</p>
<p>Yes, you can write the code for a non-sequential collection model binder. You will however face two major issues with that however. The first being that the <em>IValueProvider</em> doesn’t expose a way to iterate through all values in the <em>BindingContext</em> which you can workaround<em> </em>by hardcoding the model binder to access the current HttpRequest Form values collection (meaning that if someone decides to submit the form via Json or query parameters your model binder won’t work) or I’ve seen one more insane workaround which checks the <em>BindingContext</em> one by one from <em>CollectionName[0]</em> to <em>CollectionName[Int32.MaxValue]</em> (that’s <span style="text-decoration: underline;">2 billion</span> iterations!).</p>
<p>Second major issue is that once you create a sequential collection from the non-sequential indices and items and you have a validation error and you re-render the form view your ModelState will no longer match the data. An item that used to be at index X is now at index X-1 after another item before it was deleted, however the ModelState validation message and state still point to X, because this is what you submitted.</p>
<p>So, even a custom model binder won’t help.</p>
<p>Thankfully there is a <strong>second pattern</strong>, which mostly helps for what we want to achieve (even though I don’t think it was designed to solve exactly this):</p>
<pre class="brush: xml; title: ; notranslate">&lt;input type=&quot;hidden&quot; name=&quot;FavouriteMovies.Index&quot; value=&quot;indexA&quot;/&gt;
&lt;input name=&quot;FavouriteMovies[indexA].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;input name=&quot;FavouriteMovies[indexA].Rating&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;input type=&quot;hidden&quot; name=&quot;FavouriteMovies.Index&quot; value=&quot;indexB&quot;/&gt;
&lt;input name=&quot;FavouriteMovies[indexB].Title&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;
&lt;input name=&quot;FavouriteMovies[indexB].Rating&quot; type=&quot;text&quot; value=&quot;&quot; /&gt;</pre>
</p>
<p>Notice how we have introduced an “.Index” hidden field for each collection item. By doing that we tell ASP.NET MVC’s model binding “Hey, don’t look for a standard numeric collection index, but instead look for the custom Index value we have specified and just get me the list of items in a collection when you are done”. How does this help?</p>
<ol>
<li>We can specify any index value we want</li>
<li>The index doesn’t have to be sequential and items will be put in the collection in the order they are in the HTML when submitted.</li>
</ol>
<p>Bam! That’s solves most, but not all of our problems.</p>
<h3>The Solution</h3>
<p>Firstly, ASP.NET MVC doesn’t have HTML helpers to generate the “[something].Index” pattern which is major problem since it means we can’t use validation and custom editors. We can fix that by utilizing some ASP.NET templating fu. What we are going to do is move the Movie editor to a its own partial view (MovieEntryEditor.cshtml):</p>
<pre class="brush: xml; title: ; notranslate">@model CollectionEditing.Models.Movie
           
&lt;li style=&quot;padding-bottom:15px&quot;&gt;
    @using (Html.BeginCollectionItem(&quot;FavouriteMovies&quot;)) {
        &lt;img src=&quot;@Url.Content(&quot;~/Content/images/draggable-icon.png&quot;)&quot; style=&quot;cursor: move&quot; alt=&quot;&quot;/&gt;

        @Html.LabelFor(model =&gt; model.Title)
        @Html.EditorFor(model =&gt; model.Title)
        @Html.ValidationMessageFor(model =&gt; model.Title)

        @Html.LabelFor(model =&gt; model.Rating)
        @Html.EditorFor(model =&gt; model.Rating)
        @Html.ValidationMessageFor(model =&gt; model.Rating)

        &lt;a href=&quot;#&quot; onclick=&quot;$(this).parent().remove();&quot;&gt;Delete&lt;/a&gt;
    }
&lt;/li&gt;
</pre>
</p>
<p>And update our Edit view to use it:</p>
<p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;movieEditor&quot; style=&quot;list-style-type: none&quot;&gt;
    @foreach (Movie movie in Model.FavouriteMovies) {
        Html.RenderPartial(&quot;MovieEntryEditor&quot;, movie);
    }
&lt;/ul&gt;
&lt;p&gt;&lt;a id=&quot;addAnother&quot; href=&quot;#&quot;&gt;Add another&lt;/a&gt;</pre>
</p>
<p>Notice two things – firstly the Movie partial edit view uses standard Html helpers and secondly there is a call to something custom called <em>Html.BeginCollectionItem. </em>You might even ask yourself: Wait a second. This won’t work, because the partial view will produce names such as “Title” instead of “FavouriteMovies[xxx].Title”, so let me show you the source code of <em>Html.BeginCollectionItem</em>:</p>
<pre class="brush: csharp; title: ; notranslate">public static IDisposable BeginCollectionItem&lt;TModel&gt;(this HtmlHelper&lt;TModel&gt; html,                                                       string collectionName)
{
    string itemIndex = Guid.NewGuid().ToString();
    string collectionItemName = String.Format(&quot;{0}[{1}]&quot;, collectionName, itemIndex);

    TagBuilder indexField = new TagBuilder(&quot;input&quot;);
    indexField.MergeAttributes(new Dictionary&lt;string, string&gt;() {
        { &quot;name&quot;, String.Format(&quot;{0}.Index&quot;, collectionName) },
        { &quot;value&quot;, itemIndex },
        { &quot;type&quot;, &quot;hidden&quot; },
        { &quot;autocomplete&quot;, &quot;off&quot; }
    });

    html.ViewContext.Writer.WriteLine(indexField.ToString(TagRenderMode.SelfClosing));
    return new CollectionItemNamePrefixScope(html.ViewData.TemplateInfo, collectionItemName);
}

private class CollectionItemNamePrefixScope : IDisposable
{
    private readonly TemplateInfo _templateInfo;
    private readonly string _previousPrefix;

    public CollectionItemNamePrefixScope(TemplateInfo templateInfo, string collectionItemName)
    {
        this._templateInfo = templateInfo;

        _previousPrefix = templateInfo.HtmlFieldPrefix;
        templateInfo.HtmlFieldPrefix = collectionItemName;
    }

    public void Dispose()
    {
        _templateInfo.HtmlFieldPrefix = _previousPrefix;
    }
}</pre>
</p>
<p>This helper does two things:</p>
<ul>
<li>Appends a hidden Index field to the output with a random GUID value (remember that using the .Index pattern an index can be any string)</li>
<li>Scopes the execution of the helper via an <em>IDisposable</em> and sets the template rendering context (html helperes and display/editor templates) to be “<em>FavouriteMovies[GUID].</em>”, so we end up with HTML like this:</li>
</ul>
<p>
<pre class="brush: xml; title: ; notranslate">&lt;input autocomplete=&quot;off&quot; name=&quot;FavouriteMovies.Index&quot; type=&quot;hidden&quot; value=&quot;6d85a95b-1dee-4175-bfae-73fad6a3763b&quot; /&gt;
&lt;label&gt;Title&lt;/label&gt;
&lt;input class=&quot;text-box single-line&quot; name=&quot;FavouriteMovies[6d85a95b-1dee-4175-bfae-73fad6a3763b].Title&quot; type=&quot;text&quot; value=&quot;Movie 1&quot; /&gt;
&lt;span class=&quot;field-validation-valid&quot;&gt;&lt;/span&gt;</pre>
</p>
<p>This solves the problem of using Html field templates and basically reusing ASP.NET facilities instead of having to write html by hand, but it leads me to the second quirk that we need to address.</p>
<p>Let me show you the second and final problem. Disable client side validation and delete the title of e.g. “Movie 2” and click submit. Validation will fail, because Title of a movie is a required field, but while we are shown the edit form again<strong> there are no validation messages</strong>:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image4.png" rel="shadowbox[sbpost-786];player=img;"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://ivanz.com/wp-content/uploads/2011/06/image_thumb4.png" border="0" alt="image" width="544" height="174" /></a></p>
<p>Why is that? It’s the same problem I mentioned earlier in this post. Each time we render the view we assign different names to the fields, which do not match the ones submitted and leads to a <em>ModelState </em>inconsistency. We have to figure out how to persist the name and more specifically the Index across requests. We have two options:</p>
<ol>
<li>Add a hidden CollectionIndex field and CollectionIndex property on the <em>Movie</em> object to persist the <em>FavouriteMovies.Index</em>. This however is intrusive and suboptimal.</li>
<li>Instead of polluting the <em>Movie</em> object with an extra property be smart and in our helper <em>Html.BeginCollectionItem</em> reapply/reuse the submitted <em>FavouriteMovies.Index</em> form values.</li>
</ol>
<p>Let’s replace in <em>Html.BeginCollectionItem</em> this line:</p>
<p>
<pre class="brush: csharp; title: ; notranslate">string itemIndex = Guid.New().ToString();</pre>
<p>with:</p>
<pre class="brush: csharp; title: ; notranslate">string itemIndex = GetCollectionItemIndex(collectionIndexFieldName);</pre>
</p>
<p>And here&#8217; is the code for GetCollectionItemIndex:</p>
<pre class="brush: csharp; title: ; notranslate">private static string GetCollectionItemIndex(string collectionIndexFieldName)
{
    Queue&lt;string&gt; previousIndices = (Queue&lt;string&gt;) HttpContext.Current.Items[collectionIndexFieldName];
    if (previousIndices == null) {
        HttpContext.Current.Items[collectionIndexFieldName] = previousIndices = new Queue&lt;string&gt;();

        string previousIndicesValues = HttpContext.Current.Request[collectionIndexFieldName];
        if (!String.IsNullOrWhiteSpace(previousIndicesValues)) {
            foreach (string index in previousIndicesValues.Split(','))
                previousIndices.Enqueue(index);
        }
    }

    return previousIndices.Count &gt; 0 ? previousIndices.Dequeue() : Guid.NewGuid().ToString();
}</pre>
</p>
<p>We get all submitted values for e.g. “<em>FavouriteMovie.Index</em>” put them in a queue, which we store for the duration of the request. Each time we render a collection item we dequeue its old index value and if none is available we generate a new one. That way we preserve the Index across requests and can have a consistent <em>ModelState</em> and see validation errors and messages:</p>
<p><a href="http://ivanz.com/wp-content/uploads/2011/06/image5.png" rel="shadowbox[sbpost-786];player=img;"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://ivanz.com/wp-content/uploads/2011/06/image_thumb5.png" border="0" alt="image" width="684" height="150" /></a></p>
<p>All that is left is to implement the “Add another” button functionality and we can do that easily by appending a new row to the movie editor, which we can fetch using Ajax and use our existing MovieEntryEditor.cshtml partial view like that:</p>
<p>
<pre class="brush: csharp; title: ; notranslate">public ActionResult MovieEntryRow()
{
    return PartialView(&quot;MovieEntryEditor&quot;);
}</pre>
</p>
<p>And then add the follwing &#8220;Add Another&#8221; click handler:</p>
<p>
<pre class="brush: jscript; title: ; notranslate">$(&quot;#addAnother&quot;).click(function () {
    $.get('/User/MovieEntryRow', function (template) {
        $(&quot;#movieEditor&quot;).append(template);
    });
});</pre>
<p>Done.</p>
<h3>Conclusion</h3>
<p>While not immediately obvious editing variable length reorderable collections with standard ASP.NET MVC is possible and what I like about this approach is that:</p>
<ul>
<li>We can keep using traditional ASP.NET html helpers, editor and display templates (Html.EditorFor, etc.) with in our collection editing</li>
<li>We can make use of the ASP.NET MVC model validation client and server side</li>
</ul>
<p>What I don’t like that much however is:</p>
<ul>
<li>That we have to use an AJAX request to append a new row to the editor.</li>
<li>That we need to use the name of the collection in the movie editor partial view, but otherwise when doing the standalone AJAX get request the name context won’t be properly set for the partial template fields.</li>
</ul>
<p>I would love to hear your thoughts. The sample source code is available on my <a href="http://github.com/ivanz/ASP.NET-MVC-Collection-Editing" target="_blank">GitHub</a></p>
<p>Next: <strong><a href="http://ivanz.com/2011/06/20/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-2/">Part 2 and how to avoid having an AJAX request with the use of jQuery Templates</a></strong></p>
 <img src="http://ivanz.com/?feed-stats-post-id=786" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Java BDD with JBehave and Watij in Eclipse with JUnit</title>
		<link>http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/</link>
		<comments>http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/#comments</comments>
		<pubDate>Wed, 25 May 2011 17:29:42 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=762</guid>
		<description><![CDATA[<a href="http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/" title="Java BDD with JBehave and Watij in Eclipse with JUnit"></a>The purpose of this post is to explain how to write BDD acceptance tests in Java using the gherkin syntax, run those with JUnit and implement them using Web Browser automation. Before I begin let me assure you that I &#8230;<p class="read-more"><a href="http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/">Read more &#187;</a></p>]]></description>
	<a href="http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/" title="Java BDD with JBehave and Watij in Eclipse with JUnit"></a>			<content:encoded><![CDATA[<p>The purpose of this post is to explain how to write BDD acceptance tests in Java using the gherkin syntax, run those with JUnit and implement them using Web Browser automation.</p>
<p>Before I begin let me assure you that I haven&#8217;t left the .NET church for the Java one and while I really don&#8217;t enjoy writing in Java and using Eclipse sometimes a man has to do what a man has to do.</p>
<p>So yeah I spend an afternoon trying to figure out the state of BDD (Behavior Driven Development) tools for Java and it&#8217;s pretty poor so far. If you want to write gherkin syntax based behavioral specifications, which are executable inside Eclipse as JUnit tests you are stuck only with <a href="http://jbehave.org/">JBehave</a>. JBehave however is a monster with poor documentation, not so easily discoverable fluent API and little to none third party documentation content on forums and sites. BTW don&#8217;t get fooled like me &#8211; insetad of getting the core package you want to get the Web package because the latter has all the .jar dependencies bundled unlike the first one. Enough bashing, lets get down to business.</p>
<p>Let&#8217;s say we have the following &#8220;Search&#8221; story and a more specific scenario &#8211; &#8220;display an error dialog if I don&#8217;t fill in the search form&#8221;:</p>
<pre class="brush: plain; title: ; notranslate">Narrative: I should be able to search

Scenario: I should see an error if I try to search without filling in the search form fields.

When I open 'http://mysite.com'
When I click on the 'Search' button
Then I should see an error</pre>
<p>First thing you will notice is that JBehave doesn&#8217;t support the &#8220;And&#8221; keyword so we can&#8217;t wring &#8220;When I open &#8230; AND I click on the Seach button&#8221;.</p>
<p>Similar to other gherkin/cucumber based frameworks JBehave allows us to implement each step of the scenario as a method in a class, which optionally takes parameters mapped to words from the scenario. The above one can be stubbed like bellow. Also not that if properly configured you can make JBehave junit runner spit out the stubs for you to copy paste in your code (more about that later):</p>
<pre class="brush: java; title: ; notranslate">
public class Search
{
	@When(&quot;I open '$page'&quot;)
	public void whenIOpen(String page)
	{
		// TODO
	}

	@When(&quot;I click on the '$buttonText' button&quot;)
	public void whenIClickOnTheButton(String buttonText)
	{
		// TODO
	}

	@Then(&quot;I should see an error&quot;)
	public void thenIShouldSeeAnError(){
		// TODO
	}
}</pre>
<p>To implement the browser automation in Java there exist a Java variant of the Ruby watir library (and the .NET Watin library) called &#8230; surprise&#8230; watiJ. It&#8217;s available <a href="http://watij.com/">here</a>. Major pitfall with it though is that it actually embeds the IE COM component and mozilla&#8217;s ghecko engine instead launching the real IE/Firefox (like the above mentioned framework do) and it only supports IE6 and I saw some C++ runtime problems with the ghecko engine. Nevertheless to give you a feel of how the above tests can be implemented:</p>
<pre class="brush: java; title: ; notranslate">
public class Search extends StoryBase {

	@When(&quot;I open '$page'&quot;)
	public void whenIOpen(String page)
	{
		WebBrowser.open(page).pauseUntilReady();
	}

	@When(&quot;I click on the '$buttonText' button&quot;)
	public void whenIClickOnTheButton(String buttonText)
	{
		Tag button = WebBrowser.find.button().with.name(&quot;search&quot;);
		assertNotNull(button);
		button.click().pauseUntilReady();
	}

	@Then(&quot;I should see an error&quot;)
	public void thenIShouldSeeAnError(){
		Tag errorDialogTitleDiv = WebBrowser.find.span().with.className(&quot;dijitDialogTitle&quot;);
		assertNotNull(errorDialogTitleDiv);
		assertEquals(&quot;Error&quot;, errorDialogTitleDiv.get.innerHTML());
	}
}</pre>
<p>Now, how about running them? A few things before that:</p>
<ul>
<li>JBehave expects you to save stories as .story files in your source code tree</li>
<li>JBehave expects you to implement and configure problematically a <em>JUnitStory </em>for each story, so that it&#8217;s runnable through JUnit.</li>
<li>It will take your JUnitStory subclass implementation &#8211; for example &#8220;<em>HelloWorldStory extends JUnitStory&#8221; </em>and look for the plain text file <em>hello_world_story.story</em></li>
</ul>
<p>To save myself from having to configure each story  I present you my <em>StoryBase </em>base class, which:</p>
<ul>
<li>Initializes WatiJ and exposes it to subclasses</li>
<li>Configures JBehave to look for the .story files in the same directory as the class.</li>
<li>Configures JBehave/JUnit to look for the steps test methods of a story scenario in the subclass.</li>
<li>Configures JBehave to print out detailed information in the Console whilst running (such as the method stubs if any are missing)</li>
<li>Configures JBehave to spit out HTML report in <em>myproject/target/jbehave-report/</em></li>
</ul>
<p>Here it is:</p>
<pre class="brush: java; title: ; notranslate">
public abstract class StoryBase extends JUnitStory {
    protected final static WebSpec WebBrowser = new WebSpec().ie();

    @Override
    public Configuration configuration() {
        return new MostUsefulConfiguration()
            .useStoryLoader(new LoadFromClasspath(this.getClass().getClassLoader()))
    	    .useStoryReporterBuilder(
    	    		new StoryReporterBuilder()
    	    			.withDefaultFormats()
    	    			.withFormats(Format.HTML, Format.CONSOLE)
    	    			.withRelativeDirectory(&quot;jbehave-report&quot;)
			);
    }

    @Override
    public List candidateSteps() {
        return new InstanceStepsFactory(configuration(), this).createCandidateSteps();
    }
}
</pre>
<p>Then all that&#8217;s left is to make the Search class extend the StoryBase class and it is now runnable in JUnit inside and outside Eclipse.</p>
<pre class="brush: java; title: ; notranslate">public class Search extends StoryBase {
}</pre>
<p><a href="http://ivanz.com/wp-content/uploads/2011/05/Untitled.png" rel="shadowbox[sbpost-762];player=img;"><img class="aligncenter size-full wp-image-764" title="Project Tree" src="http://ivanz.com/wp-content/uploads/2011/05/Untitled.png" alt="" width="178" height="108" /></a><br />
<a href="http://ivanz.com/wp-content/uploads/2011/05/junit.png" rel="shadowbox[sbpost-762];player=img;"><img class="aligncenter size-full wp-image-763" title="junit" src="http://ivanz.com/wp-content/uploads/2011/05/junit.png" alt="" width="649" height="85" /></a></p>
<p>&nbsp;</p>
 <img src="http://ivanz.com/?feed-stats-post-id=762" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2011/05/25/java-bdd-with-jbehave-and-watij-in-eclipse-with-junit/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
