<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.codeville.net/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.codeville.net/~d/styles/itemcontent.css" type="text/css" media="screen"?><!-- generator="wordpress/2.3.1" --><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Steve Sanderson's blog</title>
	<link>http://blog.codeville.net</link>
	<description>mostly about ASP.NET MVC</description>
	<pubDate>Fri, 11 Jul 2008 15:53:02 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.codeville.net/SteveCodeville" type="application/rss+xml" /><item>
		<title>Overriding IIS6 wildcard maps on individual directories</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/328761664/</link>
		<comments>http://blog.codeville.net/2008/07/07/overriding-iis6-wildcard-maps-on-individual-directories/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 10:14:53 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/07/07/overriding-iis6-wildcard-maps-on-individual-directories/</guid>
		<description><![CDATA[Many thanks to Duncan Smart whose comment on my previous post about deploying ASP.NET MVC applications to IIS 6 gives us a further option. It turns out that even though IIS Manager only lets you configure wildcard maps on a per-application level, IIS itself allows you to configure them on a per-directory level.
Recap: The goal [...]]]></description>
			<content:encoded><![CDATA[<p>Many thanks to <a href="http://blog.dotsmart.net/" target="_blank">Duncan Smart</a> whose comment on my previous post about <a href="http://blog.codeville.net/?p=93" target="_blank">deploying ASP.NET MVC applications to IIS 6</a> gives us a further option. It turns out that even though IIS Manager only lets you configure wildcard maps on a per-application level, IIS itself allows you to configure them on a <strong>per-directory</strong> level.</p>
<blockquote><p><em>Recap:</em> The goal here is to deploy ASP.NET MVC applications to IIS 6, keeping the clean, extensionless URLs (which requires a wildcard map so that all URLs are processed by ASP.NET, or some tricky URL-rewriting), but without incuring the performance penalty of letting static files get processed by ASP.NET. See the previous post for more details.</p>
</blockquote>
<p>So, if you can be disciplined and keep all your static content inside your /Content folder, you can use a normal wildcard map at the root level to get ASP.NET MVC to handle all incoming URLs, even without any &#8220;filename extensions&#8221; in the URLs, but then also <em>disable</em> that wildcard map on the /Content folder and below, allowing those static files to be processed natively by IIS (which performs much better).</p>
<h4>How to set it up</h4>
<p>First, deploy your application and use a wilcard map as <a href="http://blog.codeville.net/?p=93" target="_blank">explained before</a>. Next, find out the &#8220;identifier&#8221; of your application by looking at IIS Manager:</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/07/image1.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="244" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/07/image-thumb1.png" width="663" border="0"></a> </p>
<p>Now, to remove the wildcard map on the /Content subdirectory, open a command prompt, go to <strong>c:\Inetpub\AdminScripts</strong>, and run:</p>
<pre>
adsutil.vbs SET /W3SVC/105364569/root/Content/ScriptMaps ""
</pre>
<p>&#8230; replacing 105364569 with the &#8220;identifier&#8221; number of your application. (Also, you could replace &#8220;Content&#8221; with the path to any other directory.)</p>
<p>That does it! Your /Content folder will now bypass the wildcard mapping, and its files will be served natively by IIS.</p>
<h5>Alternative</h5>
<p>If you don&#8217;t like to use adsutil.vbs, you can achieve the same by exploiting what appears to be a bug in IIS Manager. Turn your subdirectory into an application (from its Directory tab, click &#8220;Create&#8221;). Then edit its script mappings to remove aspnet_isapi.dll. Then go back and &#8220;Remove&#8221; the application you just created. The metabase&#8217;s new ScriptMaps value will be retained, even though the option has now disappeared from the GUI.</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/328761664" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/07/07/overriding-iis6-wildcard-maps-on-individual-directories/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/07/07/overriding-iis6-wildcard-maps-on-individual-directories/</feedburner:origLink></item>
		<item>
		<title>Deploying ASP.NET MVC to IIS 6</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/326592360/</link>
		<comments>http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/#comments</comments>
		<pubDate>Fri, 04 Jul 2008 11:43:10 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/</guid>
		<description><![CDATA[Deploying ASP.NET MVC applications to IIS 6 always causes confusion at first. You&#8217;ve been coding in Visual Studio 2008, seeing your lovely clean URLs work nicely in the built-in web server, you stick the code on some Windows Server 2003 machine, and then wham! It&#8217;s all like 404 Not found&#160; and you&#8217;re like hey dude [...]]]></description>
			<content:encoded><![CDATA[<p>Deploying ASP.NET MVC applications to IIS 6 always causes confusion at first. You&#8217;ve been coding in Visual Studio 2008, seeing your lovely clean URLs work nicely in the built-in web server, you stick the code on some Windows Server 2003 machine, and then wham! It&#8217;s all like <em>404 Not found</em>&nbsp; and you&#8217;re like <em>hey dude that&#8217;s not cool</em>. </p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/07/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="327" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/07/image-thumb.png" width="604" border="0"></a> </p>
<p>This happens because IIS 6 only invokes ASP.NET when it sees a &#8220;filename extension&#8221; in the URL that&#8217;s mapped to <strong>aspnet_isapi.dll</strong> (which is a C/C++ ISAPI filter responsible for invoking ASP.NET). Since routing is a .NET <strong>IHttpModule</strong> called <strong>UrlRoutingModule</strong>, it doesn&#8217;t get invoked unless ASP.NET itself gets invoked, which only happens when <strong>aspnet_isapi.dll</strong> gets invoked, which only happens when there&#8217;s a <strong>.aspx</strong> in the URL. So, no <strong>.aspx</strong>, no <strong>UrlRoutingModule</strong>, hence the 404.</p>
<p>I&#8217;d say you&#8217;ve got four ways around this:</p>
<h4>Option 1: Use a wildcard mapping for aspnet_isapi.dll</h4>
<p>This tells IIS 6 to process <em>all </em>requests using ASP.NET, so routing is always invoked, and there&#8217;s no problem. It&#8217;s dead easy to set up: open IIS manager, right-click your app, go to <em>Properties</em>, then <em>Home Directory </em>tab, then click <em>Configuration</em>. Under <em>Wildcard application maps</em>, click <em>Insert</em> (not <em>Add</em>, which is confusingly just above),&nbsp; then enter <strong>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll</strong> for &#8220;Executable&#8221;, and uncheck <em>Verify that file exists</em>. </p>
<p>Done! Routing now just behaves as it always did in VS2008&#8217;s built-in server.</p>
<p>Unfortunately, this also tells IIS to use ASP.NET to serve <em>all</em> requests, including for static files. It will work, because ASP.NET has a built-in <strong>DefaultHttpHandler</strong> that does it, but <a href="http://sticklebackplastic.com/2006/10/9/The+continuing+saga+of+StaticFileHandler++meet+DefaultHttpHandler.aspx">depending on what you do during the request</a>, it might use StaticFileHandler to serve the request. StaticFileHandler is much less efficient than IIS natively. You see, it <em>always</em> reads the files from disk for every request, not caching them in memory. It doesn&#8217;t send Cache-Control headers that you might have configured in IIS, so browsers won&#8217;t cache it properly. It doesn&#8217;t do HTTP compression. However, if you can avoid interfering with the request, DefaultHttpHandler will pass control back to IIS for native processing, which is much better.</p>
<p>For small intranet applications, wildcard mappings are probably the best choice. Yes, it impacts performance slightly, but that might not be a problem for you. Perhaps you have better things to worry about.</p>
<p>For larger public internet applications, you may need a solution that delivers better performance.</p>
<p style="border:1px solid blue; padding:5px; margin-bottom:20px;"><i><b>Update:</b> It turns out that you can <a href="http://blog.codeville.net/?p=96">disable wildcard maps on selected subfolders</a>, which may give you the best of both worlds.</i></p>
<h4>Option 2: Put .aspx in all your route entries&#8217; URL patterns</h4>
<p>If you don&#8217;t mind having .aspx in your URLs, just go through your routing config, adding .aspx before a forward-slash in each pattern. For example, use <strong>{controller}.aspx/{action}/{id}</strong> or <strong>myapp.aspx/{controller}/{action}/{id}</strong>. <em>Don&#8217;t </em>put .aspx inside the curly-bracket parameter names, or into the &#8216;default&#8217; values, because it isn&#8217;t really part of the controller name - it&#8217;s just in the URL to satisfy IIS.</p>
<p>Now your application will be invoked just like a traditional ASP.NET app. IIS still handles static files. This is probably the easiest solution in shared hosting scenarios. Unfortunately, you&#8217;ve spoiled your otherwise clean URL schema.</p>
<h4>Options 3: Use a custom filename extension in all your URL patterns</h4>
<p>This is the same as the above, except substituting something like <b>.mvc</b> instead of <b>.aspx</b>. It doesn&#8217;t really create any advantage, other than showing off that you&#8217;re using ASP.NET MVC. </p>
<p>Just update your route entries as described above, except putting .mvc instead of .aspx. Next, register a new ISAPI mapping: Open IIS manager, right-click your app, go to <em>Properties</em>, then <em>Home Directory </em>tab, then click <em>Configuration. </em>On the <em>Mappings</em> tab, click <em>Add</em>, then enter <strong>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll</strong> for &#8220;Executable&#8221;, <strong>.mvc</strong> (or whatever extension you&#8217;re using) for &#8220;Extension&#8221;, and uncheck <em>Verify that file exists</em>. Leave <em>Script engine</em> checked (unless your app has <em>Execute</em> permission) and leave <em>All verbs</em> selected unless you specifically want to filter HTTP methods.</p>
<p>That&#8217;s it - you&#8217;re now using a custom extension. Unfortunately, it&#8217;s still a bit of an eyesore on your otherwise clean URL schema.</p>
<h4>Option 4: Use URL rewriting</h4>
<p>This is a trick to make IIS think there&#8217;s a filename extension in the URL, even though there isn&#8217;t. It&#8217;s the hardest solution to implement, but the only one that gives totally clean URLs without any significant drain on performance.</p>
<p>Ben Scheirman came up with <a href="http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx" target="_blank">a great post on this subject</a>, but I&#8217;m adapting the technique slightly so as to avoid needing to change my routing configuration in any way. Here&#8217;s how it works for me:</p>
<blockquote><p>1. As an extensionless request arrives, we have a 3rd-party ISAPI filter that rewrites the request to add a known extension: .aspx.</p>
<p>2. IIS sees the extension, and maps it to aspnet_isapi.dll, and hence into ASP.NET</p>
<p>3. Before routing sees the request, we have an Application_BeginRequest() handler that rewrites the URL <em>back</em> to its original, extensionless form</p>
<p>4. Routing sees the extensionless URL and behaves normally.</p>
</blockquote>
<p>Since the URL gets un-rewritten in step 3, you don&#8217;t have to do anything funny to make outbound URL generation work.</p>
<h5>How to do it</h5>
<p>First, download and install Helicon&#8217;s <a href="http://www.isapirewrite.com/" target="_blank">ISAPI_Rewrite</a>. You can use the freeware edition, version 2, though beware this will affect <strong>all</strong> the sites on your server. If you need to localize the rewriting to a particular app or virtual directory, you&#8217;ll need one of the paid-for editions.</p>
<p>Now edit ISAPI_Rewrite&#8217;s configuration (Start -&gt; All programs -&gt; Helicon -&gt; ISAPI_Rewrite -&gt; httpd.ini), and add:</p>
<pre>
# If you're hosting in a virtual directory, enable these lines,
# entering the path of your virtual directory.
#UriMatchPrefix /myvirtdir
#UriFormatPrefix /myvirtdir

# Add extensions to this rule to avoid them being processed by ASP.NET
RewriteRule (.*)\.(css|gif|png|jpeg|jpg|js|zip) $1.$2 [I,L]

# Normalizes the homepage URL to /
RewriteRule /home(\?.*)? /$1 [I,RP,L]
RewriteRule / /home [I] 

# Prefixes URLs with "rewritten.aspx/", so that ASP.NET handles them
RewriteRule /(.*) /rewritten.aspx/$1 [I]
</pre>
<p>This excludes known, static files (CSS, GIF etc.), but for the rest, it prefixes the URL with <strong>/rewritten.aspx</strong>, making ASP.NET kick in. As a bonus, it normalizes any requests for /home to simply / via a 301 redirection, helping out with your SEO. Save this file, and restart IIS (run iisreset.exe).</p>
<p>That&#8217;s implemented step 1. Now, to implement step 3, add the following handler to your Global.asax.cs file:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">protected</span> <span style="color: #0000FF;">void</span> Application_BeginRequest<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">Object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    HttpApplication app = sender <span style="color: #0000FF;">as</span> HttpApplication;
    <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>app != <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>app.<span style="color: #0000FF;">Request</span>.<span style="color: #0000FF;">AppRelativeCurrentExecutionFilePath</span> == <span style="color: #A31515;">&quot;~/rewritten.aspx&quot;</span><span style="color: #000000;">&#41;</span>
            app.<span style="color: #0000FF;">Context</span>.<span style="color: #0000FF;">RewritePath</span><span style="color: #000000;">&#40;</span>
                app.<span style="color: #0000FF;">Request</span>.<span style="color: #0000FF;">Url</span>.<span style="color: #0000FF;">PathAndQuery</span>.<span style="color: #0000FF;">Replace</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;/rewritten.aspx&quot;</span>, <span style="color: #A31515;">&quot;&quot;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This detects rewritten URLs, and un-rewrites them. That does it! (Or at least it works on my machine - please share your experiences.) </p>
<p>Now you&#8217;ve got clean, extensionless URLs on IIS 6 (and probably on IIS5, though I haven&#8217;t tried), without using a wildcard map, and without interfering with IIS&#8217;s efficient handling of static files.</p>
<h4>Bonus option 5: Upgrade to Windows Server 2008 and IIS 7</h4>
<p>Of course, it&#8217;s <em>much</em> easier with IIS 7, because it natively supports .NET IHttpModules, so by default you&#8217;ll have UrlRoutingModule plugged right into the server, and you don&#8217;t have to do anything weird to make it work perfectly.</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/326592360" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/</feedburner:origLink></item>
		<item>
		<title>ASP.NET MVC Preview 3 is available</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/299183668/</link>
		<comments>http://blog.codeville.net/2008/05/27/aspnet-mvc-preview-3-is-available/#comments</comments>
		<pubDate>Tue, 27 May 2008 16:21:19 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/05/27/aspnet-mvc-preview-3-is-available/</guid>
		<description><![CDATA[Looks like it went up earlier today&#8230; 
Download the installer here, and the source here.
Hooray!
]]></description>
			<content:encoded><![CDATA[<p>Looks like it went up earlier today&#8230; </p>
<p>Download the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=92F2A8F0-9243-4697-8F9A-FCF6BC9F66AB&amp;displaylang=en" target="_blank">installer here</a>, and the <a href="http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=13792" target="_blank">source here</a>.</p>
<p>Hooray!</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/299183668" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/05/27/aspnet-mvc-preview-3-is-available/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/05/27/aspnet-mvc-preview-3-is-available/</feedburner:origLink></item>
		<item>
		<title>Announcing Pro ASP.NET MVC Framework (Apress)</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/293577671/</link>
		<comments>http://blog.codeville.net/2008/05/19/announcing-pro-aspnet-mvc-framework-apress/#comments</comments>
		<pubDate>Mon, 19 May 2008 15:51:48 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Pro ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/05/19/announcing-pro-aspnet-mvc-framework-apress/</guid>
		<description><![CDATA[I&#8217;m very excited to say that I&#8217;m working on an ASP.NET MVC book for Apress!
There&#8217;s such a buzz around the as-yet-unreleased MVC framework - you can hardly move for blog posts, screen casts, sample applications, etc. - but when this thing finally gets released, many developers will benefit from a single, coherent, up-to-date treatment of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.codeville.net/wp-content/uploads/2008/05/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="240" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/05/image-thumb.png" width="240" align="left" border="0"></a>I&#8217;m very excited to say that I&#8217;m working on an <a href="http://www.apress.com/book/view/9781430210078" target="_blank">ASP.NET MVC book for Apress</a>!</p>
<p>There&#8217;s such a buzz around the as-yet-unreleased MVC framework - you can hardly move for blog posts, screen casts, sample applications, etc. - but when this thing finally gets released, many developers will benefit from a single, coherent, up-to-date treatment of the entire subject.</p>
<p>My target audience is C# developers with some ASP.NET knowledge, so if you&#8217;re in this group, you will (hopefully) find this book contains the right blend of theory, tutorials, and reference material to make you productive, fast. As well as covering the MVC framework in depth, and building a meaty e-commerce application from scratch, you&#8217;ll also learn about the relevant architectures, design patterns, open-source tools, and automated testing techniques. Not to mention security issues, deployment guides, and so on&#8230;</p>
<p>This hasn&#8217;t been a tightly-guarded secret: the book has been available for <a href="http://www.amazon.com/Pro-ASP-NET-MVC-Framework/dp/1430210079/" target="_blank">pre-order on Amazon</a>* for weeks already. If you have any comments or suggestions for things you&#8217;d like to see in the book, please <a href="mailto:steve@codeville.net" target="_blank">email me</a> or leave a comment here.</p>
<p><font size="2"><em>* At the time of writing this post, not everything on Amazon&#8217;s page is entirely accurate and up-to-date - some of the book&#8217;s contents are still subject to change.</em></font></p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/293577671" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/05/19/announcing-pro-aspnet-mvc-framework-apress/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/05/19/announcing-pro-aspnet-mvc-framework-apress/</feedburner:origLink></item>
		<item>
		<title>Model-based Client-side Validation for ASP.NET MVC</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/280779502/</link>
		<comments>http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/#comments</comments>
		<pubDate>Wed, 30 Apr 2008 12:46:12 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/</guid>
		<description><![CDATA[For quite a while, I was unsure how to go about doing validation in ASP.NET MVC. By default, it&#8217;s incompatible with the ASP.NET &#60;asp:XyzValidator&#62; server controls, so this gives us an opportunity to come up with something newer and better.
There have been a couple of great efforts from the community, including Juergen Baeurle&#8217;s MVC Validator [...]]]></description>
			<content:encoded><![CDATA[<p>For quite a while, I was unsure how to go about doing validation in ASP.NET MVC. By default, it&#8217;s incompatible with the ASP.NET <strong>&lt;asp:XyzValidator&gt;</strong> server controls, so this gives us an opportunity to come up with something newer and better.</p>
<p>There have been a couple of great efforts from the community, including Juergen Baeurle&#8217;s <a href="http://www.codeproject.com/kb/aspnet/mvcvalidatortoolkit.aspx" target="_blank">MVC Validator Toolkit</a>, and Matt Hawley&#8217;s <a href="http://blog.eworldui.net/post/2008/04/MVC-UI-Validation-Framework.aspx" target="_blank">MVC UI Validation Framework</a> (now part of MVC Contrib). I wasn&#8217;t really satisfied with either, because they take validation out of the domain model and into the application&#8217;s UI (no offense guys, what you&#8217;ve done is cool).</p>
<p>So, check out my first ever screencast - 6 thrilling minutes of non-stop coding action, in which you get to add both server-side <em>and </em>breathtakingly fit client-side validation to an ASP.NET MVC application, while keeping all the validation rules right in the domain model. Whoo!</p>
<p> 	    <script type="text/javascript" src="/blogfiles/2008/April/MVCValidation/swfobject.js"></script>
<div id="media" align="center">
<div id="noUpdate">
<p style='color:red'><b>Oh noes!</b> Either your feed reader has removed the screencast, or you haven&#8217;t enabled Javascript and Flash. You&#8217;re missing out!</p>
</div>
</div>
<p> 		<script type="text/javascript">
			// <![CDATA[
			var so = new SWFObject( "/blogfiles/2008/April/MVCValidation/validation.swf", "csSWF", "400", "318", "8", "#1a4a1a");
			so.addParam( "quality", "best" );
			so.addParam( "allowFullScreen", "false" );
			so.addParam( "scale", "noscale" );
			so.addParam( "allowScriptAccess", "always" );
			so.addVariable( "autostart", "false" );
			so.write("media");			
			// ]]&gt;
		</script>
<p>For those of you that don&#8217;t have time for screencasts (like me, normally), here&#8217;s how to get the client-side validation goodness in your ASP.NET MVC application. I&#8217;m using Castle Validator for the server-side bits, and Live Validation for the client-side bits, fused into one terrifying alien beast hell-bent on ultimate data purity.</p>
<h4>Instructions</h4>
<p>1. Download and reference <a href="/blogfiles/2008/April/MVCValidation/MvcValidation.dll">MvcValidator.dll</a> and Castle.Components.Validator.dll (from the Castle project). In your master page, add a reference to the <a href="http://www.livevalidation.com/">Live Validation</a> script (preferably a local copy of it):</p>

<div class="wp_syntax"><div class="code"><pre>&lt;script src=&quot;http://www.livevalidation.com/javascripts/src/1.3/livevalidation_standalone.compressed.js&quot;&gt;&lt;/script&gt;</pre></div></div>

<p>2. Add validation attributes to your model object.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> Person
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>ValidateNonEmpty<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Please enter a name&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Name <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>ValidateNonEmpty<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Please enter an email address&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#91;</span>ValidateEmail<span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Email <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>ValidateNonEmpty<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Please enter an age&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#91;</span>ValidateInteger<span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">int</span>? Age <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>3. Drop an Html.ClientSideValidation into your view:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;% <span style="color: #0000FF;">using</span><span style="color: #000000;">&#40;</span>Html.<span style="color: #0000FF;">Form</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Home&quot;</span>, <span style="color: #A31515;">&quot;SubmitPerson&quot;</span>, FormMethod.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> %&gt;
    &lt;p&gt;Name: &lt;%= Html.<span style="color: #0000FF;">TextBox</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;MyPrefix.Name&quot;</span>, ViewData.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span> %&gt;&lt;/p&gt;
    &lt;p&gt;Email: &lt;%= Html.<span style="color: #0000FF;">TextBox</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;MyPrefix.Email&quot;</span>, ViewData.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span>%&gt;&lt;/p&gt;
    &lt;p&gt;Age: &lt;%= Html.<span style="color: #0000FF;">TextBox</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;MyPrefix.Age&quot;</span>, ViewData.<span style="color: #0000FF;">Age</span><span style="color: #000000;">&#41;</span>%&gt;&lt;/p&gt;
&nbsp;
    &lt;%= Html.<span style="color: #0000FF;">ClientSideValidation</span><span style="color: #000000;">&#40;</span>ViewData, s =&gt; <span style="color: #A31515;">&quot;MyPrefix.&quot;</span> + s<span style="color: #000000;">&#41;</span> %&gt;
    &lt;%= Html.<span style="color: #0000FF;">SubmitButton</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> %&gt;
&lt;% <span style="color: #000000;">&#125;</span> %&gt;</pre></div></div>

<p>4. Strut, pose, be smug. You&#8217;re done!</p>
<div align="center"><img src="/blogfiles/2008/April/MVCValidation/screenshot.png"/></div>
<p>Optional steps:</p>
<p>5. Add server-side validation keyed off the same validation attributes, using Castle Validator&#8217;s ValidatorRunner (the screencast shows this in action before the client-side validation).</p>
<p>6. Add <a href="http://www.livevalidation.com/examples#exampleStyles">CSS rules to get the red/green border effect</a> as shown in the screenshot.</p>
<h4>Downloads</h4>
<ul>
<li><a href="/blogfiles/2008/April/MVCValidation/MvcValidationSourceAndDemo.zip">Source code and demo project</a></li>
<li><a href="/blogfiles/2008/April/MVCValidation/MvcValidation.dll">Just the DLL, please!</a></li>
</ul>
<h4>Thoughts</h4>
<p>I&#8217;d really love to see something along these lines baked into the official MVC framework, perhaps following Castle&#8217;s example of having a pluggable system for emitting Javascript for particular validation checks, so folks could integrate it with client-side validation libraries of their choice. (In my version, I&#8217;ve just hard-coded it to work with Live Validator.)</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.codeville.net%2f2008%2f04%2f30%2fmodel-based-client-side-validation-for-aspnet-mvc%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.codeville.net%2f2008%2f04%2f30%2fmodel-based-client-side-validation-for-aspnet-mvc%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/280779502" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/</feedburner:origLink></item>
		<item>
		<title>(Server controls vs. Inline code) = (What vs. How)</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/269384888/</link>
		<comments>http://blog.codeville.net/2008/04/13/server-controls-vs-inline-code-what-vs-how/#comments</comments>
		<pubDate>Sun, 13 Apr 2008 10:19:55 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/04/13/server-controls-vs-inline-code-what-vs-how/</guid>
		<description><![CDATA[When each developer first learns about ASP.NET MVC, their immediate reaction to MVC view pages is to be shocked and appalled by the mixture of HTML markup and C# code (&#8221;inline code&#8221;). 
&#8220;What about separating presentation from logic??&#8221; they&#8217;ll cry, and of course you&#8217;ll explain the bigger picture of separation of concerns: domain logic from [...]]]></description>
			<content:encoded><![CDATA[<p>When each developer first learns about ASP.NET MVC, their immediate reaction to MVC view pages is to be shocked and appalled by the mixture of HTML markup and C# code (&#8221;inline code&#8221;). </p>
<p>&#8220;<em>What about separating presentation from logic??</em>&#8221; they&#8217;ll cry, and of course you&#8217;ll explain the bigger picture of separation of concerns: domain logic from application logic from UI logic, and how MVC adds scope for testability and cleaner code and how <strong><em>foreach </em></strong>loops beat databinding any day, and so on, mercilessly kicking WebForms&#8217;s elderly butt.</p>
<p>And of course you&#8217;re right. But each time I have to type out view code like this:</p>

<div class="wp_syntax"><div class="code"><pre>&lt;table cellspacing=&quot;0&quot;&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;ID&lt;/th&gt;
            &lt;th&gt;Product&lt;/th&gt;
            &lt;th&gt;Category&lt;/th&gt;
            &lt;th align=&quot;right&quot;&gt;Price&lt;/th&gt;
            &lt;th&gt;&lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
        &lt;% foreach(var item in ViewData.Products) { %&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;%= item.ProductID %&gt;&lt;/td&gt;
                &lt;td&gt;&lt;%= item.Name %&gt;&lt;/td&gt;
                &lt;td&gt;&lt;%= item.Category %&gt;&lt;/td&gt;
                &lt;td align=&quot;right&quot;&gt;&lt;%= item.Price.ToString(&quot;c&quot;) %&gt;&lt;/td&gt;
                &lt;td&gt;&lt;%= Html.ActionLink(&quot;Details&quot;, &quot;Show&quot;, new { ProductID = item.ProductID }) %&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;% } %&gt;
    &lt;/tbody&gt;
&lt;/table&gt;</pre></div></div>

<p>&#8230; I can&#8217;t help thinking that <em>something&#8217;s slightly not right here </em>(and honestly, I try to suppress that dark thought!). Oh don&#8217;t get me wrong, I&#8217;m a big fan of the new MVC framework, and I&#8217;d take it rather than WebForms any day, but software development technology normally progresses like this:</p>
<ul>
<li><em>Old technology</em>: Specify exactly what you want the computer to do</li>
<li><em>New technology</em>: Specify what end result you want, but let the computer work out the details</li>
</ul>
<p>Great examples of the latter bullet point are query languages like SQL or even LINQ, and many of C#&#8217;s newer features (e.g. type inference). And how about:</p>
<ul>
<li>Classic ASP: Specify exactly what HTML markup you want</li>
<li>WebForms: Specify what end result you want (e.g. a grid), and let the framework figure out what HTML markup is required</li>
<li>ASP.NET MVC: Um, specify exactly what HTML markup you want</li>
</ul>
<p>My experience is that WebForms was a great idea, for its time, but in practice it just didn&#8217;t work so well. For demoware, it&#8217;s an awesome platform, but try to build a 3-person-year project with it and it will all end in tears (but not tiers). </p>
<p>So, with MVC, we think again and take stock of where we are. HTML is still a real concern, WebForms&#8217;s abstraction layer *didn&#8217;t* save us from browser incompatibilities, and HTTP is still a stateless protocol. Time for a change of plan, back to basics and all that, but do we really have to go back to writing &lt;TABLE&gt;&lt;THEAD&gt;&lt;TR&gt;&lt;TH&gt;&#8230; etc.? It&#8217;s not hard, it&#8217;s just <em>verbose</em>. Do we need a better DSL for HTML? Is that what alternate view engines could provide?</p>
<p>The framework&#8217;s built-in HTML helpers really do help us, but they only produce individual HTML tags, not related groups of tags. Maybe we should add some new ones, e.g. <strong>Html.Table</strong>, so you could just write:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">&lt;%= Html.<span style="color: #0000FF;">Table</span><span style="color: #000000;">&#40;</span>ViewData.<span style="color: #0000FF;">Products</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> cellspacing = <span style="color: #000000;">0</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
    .<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ID&quot;</span>, i =&gt; i.<span style="color: #0000FF;">ProductID</span><span style="color: #000000;">&#41;</span>
    .<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Product&quot;</span>, i =&gt; i.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span>
    .<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Category&quot;</span>, i =&gt; i.<span style="color: #0000FF;">Category</span><span style="color: #000000;">&#41;</span>
    .<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Price&quot;</span>, i =&gt; i.<span style="color: #0000FF;">Price</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;c&quot;</span><span style="color: #000000;">&#41;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> align = <span style="color: #A31515;">&quot;right&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
    .<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;&quot;</span>, i =&gt; Html.<span style="color: #0000FF;">ActionLink</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Details&quot;</span>, <span style="color: #A31515;">&quot;Show&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> ProductID = i.<span style="color: #0000FF;">ProductID</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
%&gt;</pre></div></div>

<p>In case you do think that&#8217;s a good idea, here&#8217;s the code needed to implement it. Sorry it&#8217;s a bit long, but each method has a few overrides to give you more flexibility in how you supply parameters:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">namespace</span> StevenSanderson.<span style="color: #0000FF;">Mvc</span>.<span style="color: #0000FF;">HtmlHelpers</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> <span style="color: #0000FF;">class</span> TableHelper
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> HtmlTable&lt;T&gt; Table&lt;T&gt;<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span> HtmlHelper html, IEnumerable&lt;T&gt; data<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0000FF;">return</span> html.<span style="color: #0000FF;">Table</span>&lt;T&gt;<span style="color: #000000;">&#40;</span>data, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> HtmlTable&lt;T&gt; Table&lt;T&gt;<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span> HtmlHelper html, IEnumerable&lt;T&gt; data, <span style="color: #0000FF;">object</span> htmlAttributes<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0000FF;">return</span> html.<span style="color: #0000FF;">Table</span>&lt;T&gt;<span style="color: #000000;">&#40;</span>data, htmlAttributes.<span style="color: #0000FF;">ToPropertyList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">static</span> HtmlTable&lt;T&gt; Table&lt;T&gt;<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span> HtmlHelper html, IEnumerable&lt;T&gt; data, IDictionary&lt;string, string&gt; htmlAttributes<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">new</span> HtmlTable&lt;T&gt; <span style="color: #000000;">&#123;</span> Data = data, HtmlAttributes = htmlAttributes <span style="color: #000000;">&#125;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> HtmlTable&lt;T&gt;
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0000FF;">public</span> IEnumerable&lt;T&gt; Data; 
            <span style="color: #0000FF;">public</span> IDictionary&lt;string, string&gt; HtmlAttributes;
            <span style="color: #0000FF;">private</span> IList&lt;HtmlTableColumn&gt; columns = <span style="color: #0000FF;">new</span> List&lt;HtmlTableColumn&gt;<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #0000FF;">public</span> HtmlTable&lt;T&gt; AddColumn<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> headerText, Func&lt;T, object&gt; itemText<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">this</span>.<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span>headerText, itemText, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0000FF;">public</span> HtmlTable&lt;T&gt; AddColumn<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> headerText, Func&lt;T, object&gt; itemText, <span style="color: #0000FF;">object</span> htmlAttributes<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">this</span>.<span style="color: #0000FF;">AddColumn</span><span style="color: #000000;">&#40;</span>headerText, itemText, htmlAttributes.<span style="color: #0000FF;">ToPropertyList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0000FF;">public</span> HtmlTable&lt;T&gt; AddColumn<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">string</span> headerText, Func&lt;T, object&gt; itemText, IDictionary&lt;string, string&gt; htmlAttributes<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                columns.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> HtmlTableColumn
                <span style="color: #000000;">&#123;</span>
                    HeaderText = headerText,
                    ItemText = itemText,
                    HtmlAttributes = htmlAttributes
                <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">this</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">void</span> RenderAttributes<span style="color: #000000;">&#40;</span>HtmlTextWriter writer, IDictionary&lt;string, string&gt; attribs<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>attribs != <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> attrib <span style="color: #0000FF;">in</span> attribs<span style="color: #000000;">&#41;</span>
                        writer.<span style="color: #0000FF;">AddAttribute</span><span style="color: #000000;">&#40;</span>attrib.<span style="color: #0000FF;">Key</span>, attrib.<span style="color: #0000FF;">Value</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #0000FF;">true</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">override</span> <span style="color: #0000FF;">string</span> ToString<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0000FF;">using</span> <span style="color: #000000;">&#40;</span>StringWriter sw = <span style="color: #0000FF;">new</span> StringWriter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    HtmlTextWriter writer = <span style="color: #0000FF;">new</span> HtmlTextWriter<span style="color: #000000;">&#40;</span>sw<span style="color: #000000;">&#41;</span>;
&nbsp;
                    <span style="color: #008000;">// &lt;TABLE&gt;</span>
                    RenderAttributes<span style="color: #000000;">&#40;</span>writer, <span style="color: #0000FF;">this</span>.<span style="color: #0000FF;">HtmlAttributes</span><span style="color: #000000;">&#41;</span>;
                    writer.<span style="color: #0000FF;">RenderBeginTag</span><span style="color: #000000;">&#40;</span>HtmlTextWriterTag.<span style="color: #0000FF;">Table</span><span style="color: #000000;">&#41;</span>;
&nbsp;
                    <span style="color: #008000;">// Headers</span>
                    writer.<span style="color: #0000FF;">RenderBeginTag</span><span style="color: #000000;">&#40;</span>HtmlTextWriterTag.<span style="color: #0000FF;">Thead</span><span style="color: #000000;">&#41;</span>;
                    RenderTableRow<span style="color: #000000;">&#40;</span>writer, HtmlTextWriterTag.<span style="color: #0000FF;">Th</span>, col =&gt; col.<span style="color: #0000FF;">HeaderText</span><span style="color: #000000;">&#41;</span>;
                    writer.<span style="color: #0000FF;">RenderEndTag</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// &lt;/THEAD&gt;</span>
&nbsp;
                    <span style="color: #008000;">// Rows</span>
                    writer.<span style="color: #0000FF;">RenderBeginTag</span><span style="color: #000000;">&#40;</span>HtmlTextWriterTag.<span style="color: #0000FF;">Tbody</span><span style="color: #000000;">&#41;</span>;
                    <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span>T row <span style="color: #0000FF;">in</span> Data<span style="color: #000000;">&#41;</span>
                        RenderTableRow<span style="color: #000000;">&#40;</span>writer, HtmlTextWriterTag.<span style="color: #0000FF;">Td</span>, col =&gt; col.<span style="color: #0000FF;">ItemText</span><span style="color: #000000;">&#40;</span>row<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
                    writer.<span style="color: #0000FF;">RenderEndTag</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// &lt;/TBODY&gt;</span>
&nbsp;
                    writer.<span style="color: #0000FF;">RenderEndTag</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// &lt;/TABLE&gt;</span>
                    <span style="color: #0000FF;">return</span> sw.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">void</span> RenderTableRow<span style="color: #000000;">&#40;</span>HtmlTextWriter writer, HtmlTextWriterTag cellTag, Func&lt;HtmlTableColumn, string&gt; cellValue<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                writer.<span style="color: #0000FF;">RenderBeginTag</span><span style="color: #000000;">&#40;</span>HtmlTextWriterTag.<span style="color: #0000FF;">Tr</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">var</span> col <span style="color: #0000FF;">in</span> columns<span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    RenderAttributes<span style="color: #000000;">&#40;</span>writer, col.<span style="color: #0000FF;">HtmlAttributes</span><span style="color: #000000;">&#41;</span>;
                    writer.<span style="color: #0000FF;">RenderBeginTag</span><span style="color: #000000;">&#40;</span>cellTag<span style="color: #000000;">&#41;</span>;
                    writer.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>cellValue<span style="color: #000000;">&#40;</span>col<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
                    writer.<span style="color: #0000FF;">RenderEndTag</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// &lt;/TH&gt;</span>
                <span style="color: #000000;">&#125;</span>
                writer.<span style="color: #0000FF;">RenderEndTag</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008000;">// &lt;/TR&gt;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0000FF;">class</span> HtmlTableColumn
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> HeaderText <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
                <span style="color: #0000FF;">public</span> Func&lt;T, object&gt; ItemText <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
                <span style="color: #0000FF;">public</span> IDictionary&lt;string, string&gt; HtmlAttributes <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">static</span> IDictionary&lt;string, string&gt; ToPropertyList<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">this</span> <span style="color: #0000FF;">object</span> obj<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0000FF;">return</span> obj == <span style="color: #0000FF;">null</span> ? <span style="color: #0000FF;">null</span>
                : obj.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetProperties</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToDictionary</span><span style="color: #000000;">&#40;</span>p =&gt; p.<span style="color: #0000FF;">Name</span>, p =&gt; p.<span style="color: #0000FF;">GetValue</span><span style="color: #000000;">&#40;</span>obj, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Note that, to use this, you need to add <tt>&lt;%@ Import Namespace=&#8221;StevenSanderson.Mvc.HtmlHelpers&#8221; %></tt> to the top of your view page (probably changing the namespace to something more suitable for your project), or add the namespace to your web.config in the system.web/pages/namespaces node.</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/269384888" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/04/13/server-controls-vs-inline-code-what-vs-how/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/04/13/server-controls-vs-inline-code-what-vs-how/</feedburner:origLink></item>
		<item>
		<title>Improve scalability in ASP.NET MVC using Asynchronous requests</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/264623293/</link>
		<comments>http://blog.codeville.net/2008/04/05/improve-scalability-in-aspnet-mvc-using-asynchronous-requests/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 16:04:28 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/04/05/improve-scalability-in-aspnet-mvc-using-asynchronous-requests/</guid>
		<description><![CDATA[ASP.NET applications run with a fixed-size thread pool. By default, they have 25 threads available to handle requests. You can make the thread pool bigger if you want, but it&#8217;s not usually helpful: more contention and overhead from thread switching will eventually actually reduce the server&#8217;s throughput. But what if most of your threads are [...]]]></description>
			<content:encoded><![CDATA[<p>ASP.NET applications run with a fixed-size thread pool. By default, they have 25 threads available to handle requests. You can make the thread pool bigger if you want, but it&#8217;s not usually helpful: more contention and overhead from thread switching will eventually actually reduce the server&#8217;s throughput. But what if most of your threads are actually sitting around doing nothing, because they&#8217;re actually waiting for some external I/O operation to complete, such as a database query or a call to an external web service? Surely things could be more efficient&#8230;</p>
<p>Well yes, actually. Ever since Windows NT 4 we&#8217;ve had a notion of I/O Completion Ports (IOCP) which are a mechanism for waiting for I/O to complete without causing thread contention in the meantime. .NET has a special thread pool reserved for threads waiting on IOCP, and you can take advantage of that in your ASP.NET MVC application.</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/04/image.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="367" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/04/image-thumb.png" width="688" border="0"></a> </p>
<p>The <strong>IHttpAsyncHandler</strong>, first introduced in ASP.NET 2.0, splits request processing into two. Instead of handling an entire request in one thread (expensive I/O and all), it first does some processing in the normal ASP.NET thread pool, as per any normal request, then when it&#8217;s time for I/O, it transfers control to the I/O thread, releasing the original ASP.NET thread to get on with other requests. When the I/O signals completion (via IOCP), ASP.NET claims another, possibly different thread from its worker pool to finish off the request. Thus, the ASP.NET thread pool doesn&#8217;t get &#8216;clogged up&#8217; with threads that are actually just waiting for I/O.</p>
<h4>Adding asynchronous processing to ASP.NET MVC</h4>
<p>The MVC framework doesn&#8217;t (yet) come with any built-in support for asynchronous requests. But it&#8217;s a very extensible framework, so we can add support quite easily. First, we define <b>AsyncController</b>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> AsyncController : Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">internal</span> AsyncCallback Callback <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">internal</span> IAsyncResult Result <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">internal</span> Action&lt;IAsyncResult&gt; OnCompletion <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span> 
&nbsp;
    <span style="color: #0000FF;">protected</span> <span style="color: #0000FF;">void</span> RegisterAsyncTask<span style="color: #000000;">&#40;</span>Func&lt;AsyncCallback, IAsyncResult&gt; beginInvoke, Action&lt;IAsyncResult&gt; endInvoke<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        OnCompletion = endInvoke;
        Result = beginInvoke<span style="color: #000000;">&#40;</span>Callback<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>It&#8217;s just like a normal <strong>Controller</strong>, except it manages some internal state to do with asynchronous processing, and has the <strong>RegisterAsyncTask()</strong> method that lets you manage transitions across the gap between the two halves of <strong>IHttpAsyncHandler</strong> processing. Note: it doesn&#8217;t implement <strong>IHttpAsyncHandler</strong> itself; that&#8217;s the job of the <strong>IRouteHandler</strong> we have to set up. Unfortunately I had to reproduce most of the code from the framework&#8217;s MvcHandler, because I couldn&#8217;t just override any individual method and still get at the controller:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> AsyncMvcRouteHandler : IRouteHandler
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> IHttpHandler GetHttpHandler<span style="color: #000000;">&#40;</span>RequestContext requestContext<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">new</span> AsyncMvcHandler<span style="color: #000000;">&#40;</span>requestContext<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span> 
&nbsp;
    <span style="color: #0000FF;">class</span> AsyncMvcHandler : IHttpAsyncHandler, IRequiresSessionState
    <span style="color: #000000;">&#123;</span>
        RequestContext requestContext;
        AsyncController asyncController;
        HttpContext httpContext; 
&nbsp;
        <span style="color: #0000FF;">public</span> AsyncMvcHandler<span style="color: #000000;">&#40;</span>RequestContext context<span style="color: #000000;">&#41;</span> 
        <span style="color: #000000;">&#123;</span> 
            requestContext = context; 
        <span style="color: #000000;">&#125;</span> 
&nbsp;
        <span style="color: #008000;">// IHttpHandler members</span>
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">bool</span> IsReusable <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0000FF;">return</span> <span style="color: #0000FF;">false</span>; <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> ProcessRequest<span style="color: #000000;">&#40;</span>HttpContext httpContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0000FF;">throw</span> <span style="color: #0000FF;">new</span> NotImplementedException<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#125;</span> 
&nbsp;
        <span style="color: #008000;">// IHttpAsyncHandler members</span>
        <span style="color: #0000FF;">public</span> IAsyncResult BeginProcessRequest<span style="color: #000000;">&#40;</span>HttpContext context, AsyncCallback cb, <span style="color: #0000FF;">object</span> extraData<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008000;">// Get the controller type</span>
            <span style="color: #0000FF;">string</span> controllerName = requestContext.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">GetRequiredString</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;controller&quot;</span><span style="color: #000000;">&#41;</span>; 
&nbsp;
            <span style="color: #008000;">// Obtain an instance of the controller</span>
            IControllerFactory factory = ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetControllerFactory</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            IController controller = factory.<span style="color: #0000FF;">CreateController</span><span style="color: #000000;">&#40;</span>requestContext, controllerName<span style="color: #000000;">&#41;</span>;
            <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>controller == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0000FF;">throw</span> <span style="color: #0000FF;">new</span> InvalidOperationException<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Can't locate the controller &quot;</span> + controllerName<span style="color: #000000;">&#41;</span>;
            <span style="color: #0000FF;">try</span>
            <span style="color: #000000;">&#123;</span>
                asyncController = controller <span style="color: #0000FF;">as</span> AsyncController;
                <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>asyncController == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #0000FF;">throw</span> <span style="color: #0000FF;">new</span> InvalidOperationException<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Controller isn't an AsyncController.&quot;</span><span style="color: #000000;">&#41;</span>; 
&nbsp;
                <span style="color: #008000;">// Set up asynchronous processing</span>
                httpContext = HttpContext.<span style="color: #0000FF;">Current</span>; <span style="color: #008000;">// Save this for later</span>
                asyncController.<span style="color: #0000FF;">Callback</span> = cb;
                <span style="color: #000000;">&#40;</span>asyncController <span style="color: #0000FF;">as</span> IController<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Execute</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> ControllerContext<span style="color: #000000;">&#40;</span>requestContext, controller<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0000FF;">return</span> asyncController.<span style="color: #0000FF;">Result</span>;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0000FF;">finally</span>
            <span style="color: #000000;">&#123;</span>
                factory.<span style="color: #0000FF;">DisposeController</span><span style="color: #000000;">&#40;</span>controller<span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span> 
&nbsp;
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> EndProcessRequest<span style="color: #000000;">&#40;</span>IAsyncResult result<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            CallContext.<span style="color: #0000FF;">HostContext</span> = httpContext; <span style="color: #008000;">// So that RenderView() works</span>
            asyncController.<span style="color: #0000FF;">OnCompletion</span><span style="color: #000000;">&#40;</span>result<span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>It handles requests by supplying an <strong>AsyncMvcHandler</strong>, which implements <strong>IHttpAsyncHandler</strong>. Note that during the first half of the processing, i.e. during <strong>BeginProcessRequest()</strong>, it makes a record of the current <strong>HttpContext</strong> object. We have to restore that later, during <strong>EndProcessRequest()</strong>, because we&#8217;ll be in a new thread context by then and <strong>HttpContext</strong> will be <strong>null</strong> (and that breaks various ASP.NET facilities including WebForms view rendering).</p>
<h4>Using AsyncController</h4>
<p>It&#8217;s now very easy to handle a request asynchronously. Define a route using <b>AsyncMvcRouteHandler</b>, instead of <b>MvcRouteHandler</b>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">routes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> Route<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Default.aspx&quot;</span>, <span style="color: #0000FF;">new</span> AsyncMvcRouteHandler<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Defaults = <span style="color: #0000FF;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> controller = <span style="color: #A31515;">&quot;Home&quot;</span>, action = <span style="color: #A31515;">&quot;Index&quot;</span>, id = <span style="color: #A31515;">&quot;&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>,
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Then set up an <strong>AsyncController</strong>. In this example, we&#8217;re calling an external web service using the <strong>WebRequest</strong> class and its <strong>BeginGetResponse()</strong> method. That uses an IOCP, so won&#8217;t consume an ASP.NET worker thread while it waits: </p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> HomeController : AsyncController
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        WebRequest req = WebRequest.<span style="color: #0000FF;">Create</span><span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;http://www.example.com&quot;</span><span style="color: #000000;">&#41;</span>;
        req.<span style="color: #0000FF;">Method</span> = <span style="color: #A31515;">&quot;GET&quot;</span>;
&nbsp;
        RegisterAsyncTask<span style="color: #000000;">&#40;</span>cb =&gt; req.<span style="color: #0000FF;">BeginGetResponse</span><span style="color: #000000;">&#40;</span>cb, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>, <span style="color: #0000FF;">delegate</span><span style="color: #000000;">&#40;</span>IAsyncResult result<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            WebResponse response = req.<span style="color: #0000FF;">EndGetResponse</span><span style="color: #000000;">&#40;</span>result<span style="color: #000000;">&#41;</span>;
            <span style="color: #008000;">// Do something with the response here if you want</span>
            RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>And that&#8217;s it. The web request gets set up and started in the first half of the async processing model, then the thread gets released to serve other requests. When the web request signals completion, ASP.NET takes a different thread from its pool, and gets it to run the code inside the anonymous delegate, inheriting the request context from the first thread so it can send output to the visitor.</p>
<p>Just remember that you should only use async requests when you&#8217;re waiting for some operation on an IOCP. Don&#8217;t use it if you just going to call one of your own delegates asynchronously (e.g. using <strong>QueueUserWorkItem()</strong>) because that will come out of the ASP.NET worker thread pool and you&#8217;ll get exactly zero benefit (but more overhead).</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/264623293" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/04/05/improve-scalability-in-aspnet-mvc-using-asynchronous-requests/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/04/05/improve-scalability-in-aspnet-mvc-using-asynchronous-requests/</feedburner:origLink></item>
		<item>
		<title>Unexpected feature in Vista SP1</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/250969882/</link>
		<comments>http://blog.codeville.net/2008/03/13/unexpected-feature-in-vista-sp1/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 20:08:53 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/03/13/unexpected-feature-in-vista-sp1/</guid>
		<description><![CDATA[Wow, they&#8217;re really taking this operating system to the next level. 
 
&#8230; and perhaps even more surprising:
 
Is there anything Vista can&#8217;t do?
]]></description>
			<content:encoded><![CDATA[<p>Wow, they&#8217;re really taking this operating system to the next level. </p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/03/image.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="151" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/03/image-thumb.png" width="463" border="0"></a> </p>
<p>&#8230; and perhaps even more surprising:</p>
<p><a href="http://blog.codeville.net/wp-content/uploads/2008/03/image1.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="153" alt="image" src="http://blog.codeville.net/wp-content/uploads/2008/03/image-thumb1.png" width="480" border="0"></a> </p>
<p>Is there anything Vista <em>can&#8217;t</em> do?</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/250969882" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/03/13/unexpected-feature-in-vista-sp1/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/03/13/unexpected-feature-in-vista-sp1/</feedburner:origLink></item>
		<item>
		<title>ASP.NET MVC: Making strongly-typed ViewPages more easily</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/238983760/</link>
		<comments>http://blog.codeville.net/2008/02/21/aspnet-mvc-making-strongly-typed-viewpages-more-easily/#comments</comments>
		<pubDate>Thu, 21 Feb 2008 19:37:42 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2008/02/21/aspnet-mvc-making-strongly-typed-viewpages-more-easily/</guid>
		<description><![CDATA[When I first started using ASP.NET MVC, I had a problem with ViewData. It seemed like a bit of a pain, because you have two options:
1. Treat it as a loosely-typed dictionary, in which case you get no help from intellisense and have to keep writing typecasts all over your views (which is error-prone and [...]]]></description>
			<content:encoded><![CDATA[<p>When I first started using ASP.NET MVC, I had a problem with ViewData. It seemed like a bit of a pain, because you have two options:</p>
<p>1. Treat it as a loosely-typed dictionary, in which case you get no help from intellisense and have to keep writing typecasts all over your views (which is error-prone and ugly):</p>
<p><code><strong>Customer name: &lt;%= ((Customer)ViewData[&#8221;Customer&#8221;]).FullName %&gt;</strong></code></p>
<p>2. Treat it as a specific strongly-typed object - but which type? It&#8217;s all very well to pass in one of my domain objects (as in <code><strong>RenderView(&#8221;ShowCustomer&#8221;, customerRecord)</strong></code>), but the next minute I want to add a status message or something, and the model breaks down.</p>
<p><a href="http://codebetter.com/blogs/jeffrey.palermo/archive/2008/01/24/smartbag-for-asp-net-mvc-take-two.aspx" target="_blank">Jeffrey Palermo came up with a great idea called SmartBag</a>: it solves the problem - at least partially - by supplying an interface like ViewData.Get&lt;CatOwner&gt;() (which returns the first CatOwner object in the collection). This certainly reduces the scope for typos and the need for typecasts. Still, I wasn&#8217;t satisfied, because it gets awkward when you have more than one object of a given type (you have to revert to using string keys). </p>
<h4>A helpful convention</h4>
<p>Fairly soon, I settled down on a convention that seems effective (so far). In the code-behind file for every ViewPage, right at the top, I define a very simple data container object specific to that ViewPage:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> ShowCatViewData
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Name <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">int</span> Age <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">bool</span> HasFunnyFace <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">public</span> CatOwner Owner <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0000FF;">public</span> partial <span style="color: #0000FF;">class</span> ShowCat : ViewPage&lt;ShowCatViewData&gt;
<span style="color: #000000;">&#123;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>&#8230; and then of course render the view like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>ControllerAction<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ShowCat&quot;</span>, <span style="color: #0000FF;">new</span> ShowCatViewData <span style="color: #000000;">&#123;</span>
        Name = <span style="color: #A31515;">&quot;Moo-moo&quot;</span>,
        Age = <span style="color: #000000;">6</span>,
        HasFunnyFace = <span style="color: #0000FF;">true</span>
    <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now we have strongly-typed ViewData so we get intellisense and no need for typecasts. Because the ShowCatViewData class is specific to the ShowCat view, I don&#8217;t mind adding in extra fields (e.g. for status messages or whatever) whenever they&#8217;re needed. It doesn&#8217;t interfere with my database model. </p>
<h4>But what if my controller prefers loosely-typed dictionaries?</h4>
<p>Admittedly, sometimes it seems nice to use the dictionary syntax to construct ViewData. You can add fields incrementally, and the controller doesn&#8217;t need to know about any particular .NET class specific to the view, like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>ControllerAction<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Age&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #000000;">25</span>;
    ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;HasFunnyFace&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #0000FF;">false</span>;
    <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>nameIsKnown<span style="color: #000000;">&#41;</span>
        ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Name&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #A31515;">&quot;Frankie&quot;</span>; 
    RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ShowCat&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>&#8230; but you can&#8217;t do that if the ViewPage demands a strongly-typed ViewData object, right? </p>
<h4>Introducing AutoTypeViewPage&lt;T&gt;</h4>
<p>When you derive a ViewPage from AutoTypeViewPage&lt;T&gt;, your ViewPage suddenly gets a little bit smarter. </p>
<p>Just change this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> partial <span style="color: #0000FF;">class</span> ShowCat : ViewPage&lt;ShowCatViewData&gt; <span style="color: #000000;">&#123;</span> ... <span style="color: #000000;">&#125;</span></pre></div></div>

<p>&#8230; to this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> partial <span style="color: #0000FF;">class</span> ShowCat : AutoTypeViewPage&lt;ShowCatViewData&gt; <span style="color: #000000;">&#123;</span> ... <span style="color: #000000;">&#125;</span></pre></div></div>

<p>and now you can use <strong>any</strong> of following three syntaxes to send the ViewData, and you&#8217;ll get the exact same strongly-typed ViewData in the ASPX page: </p>
<blockquote>
<h4>Syntax #1: Old-school dictionary</h4>

<div class="wp_syntax"><div class="code"><pre class="csharp">ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Name&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #A31515;">&quot;Moo-moo&quot;</span>;
ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;Age&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #000000;">6</span>;
ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;HasFunnyFace&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #0000FF;">true</span>;
RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ShowCat&quot;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<h4>Syntax #2: Explicitly-typed ViewData object</h4>

<div class="wp_syntax"><div class="code"><pre class="csharp">RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ShowCat&quot;</span>, <span style="color: #0000FF;">new</span> ShowCatViewData <span style="color: #000000;">&#123;</span>
    Name = <span style="color: #A31515;">&quot;Moo-moo&quot;</span>,
    Age = <span style="color: #000000;">6</span>,
    HasFunnyFace = <span style="color: #0000FF;">true</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<h4>Syntax #3: Anonymously-typed object</h4>

<div class="wp_syntax"><div class="code"><pre class="csharp">RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;ShowCat&quot;</span>, <span style="color: #0000FF;">new</span> <span style="color: #000000;">&#123;</span> 
    Name = <span style="color: #A31515;">&quot;Moo-moo&quot;</span>, 
    Age = <span style="color: #000000;">6</span>, 
    HasFunnyFace = <span style="color: #0000FF;">true</span> 
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

</blockquote>
<h4>How interesting! Show me the code</h4>
<p>OK, chill out. It&#8217;s very simple:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> AutoTypeViewPage&lt;TViewData&gt; : ViewPage&lt;TViewData&gt;
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">protected</span> <span style="color: #0000FF;">override</span> <span style="color: #0000FF;">void</span> SetViewData<span style="color: #000000;">&#40;</span><span style="color: #0000FF;">object</span> viewData<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>viewData == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span> || <span style="color: #000000;">&#40;</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">&#40;</span>TViewData<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">IsAssignableFrom</span><span style="color: #000000;">&#40;</span>viewData.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #008000;">// The incoming object is already of the right type</span>
            <span style="color: #0000FF;">base</span>.<span style="color: #0000FF;">SetViewData</span><span style="color: #000000;">&#40;</span>viewData<span style="color: #000000;">&#41;</span>;
        <span style="color: #0000FF;">else</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008000;">// Convert the incoming object to a dictionary, if it isn't one already</span>
            IDictionary suppliedProps = viewData <span style="color: #0000FF;">as</span> IDictionary;
            <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>suppliedProps == <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>
                suppliedProps = viewData.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetProperties</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                                .<span style="color: #0000FF;">ToDictionary</span><span style="color: #000000;">&#40;</span>pi =&gt; pi.<span style="color: #0000FF;">Name</span>, pi =&gt; pi.<span style="color: #0000FF;">GetValue</span><span style="color: #000000;">&#40;</span>viewData, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>; 
            <span style="color: #008000;">// Construct a TViewData object, taking values from suppliedProps where available</span>
            TViewData data = Activator.<span style="color: #0000FF;">CreateInstance</span>&lt;TViewData&gt;<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #0000FF;">foreach</span> <span style="color: #000000;">&#40;</span>PropertyInfo allowedProp <span style="color: #0000FF;">in</span> <span style="color: #0000FF;">typeof</span><span style="color: #000000;">&#40;</span>TViewData<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetProperties</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span>suppliedProps.<span style="color: #0000FF;">Contains</span><span style="color: #000000;">&#40;</span>allowedProp.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    allowedProp.<span style="color: #0000FF;">SetValue</span><span style="color: #000000;">&#40;</span>data, suppliedProps<span style="color: #000000;">&#91;</span>allowedProp.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#93;</span>, <span style="color: #0000FF;">null</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #0000FF;">base</span>.<span style="color: #0000FF;">SetViewData</span><span style="color: #000000;">&#40;</span>data<span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h4>Final notes</h4>
<p>Apparently MonoRail has something vaguely related: DictionaryAdapter. It&#8217;s a bit different because what that does is take a pure interface and create a basic implementation via run-time code gen, so you don&#8217;t need a concrete implementation of the ViewData class - just an interface for it. If you were clever, you could combine that with the AutoTypeViewPage technique so that arbitrary incoming objects were converted to IMyInterface.</p>
<p>If you have any feedback, you know where to post!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.codeville.net%2f2008%2f02%2f21%2faspnet-mvc-making-strongly-typed-viewpages-more-easily%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.codeville.net%2f2008%2f02%2f21%2faspnet-mvc-making-strongly-typed-viewpages-more-easily%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/238983760" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2008/02/21/aspnet-mvc-making-strongly-typed-viewpages-more-easily/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2008/02/21/aspnet-mvc-making-strongly-typed-viewpages-more-easily/</feedburner:origLink></item>
		<item>
		<title>Client-side MVC with jMVC and ASP.NET MVC</title>
		<link>http://feeds.codeville.net/~r/SteveCodeville/~3/204591086/</link>
		<comments>http://blog.codeville.net/2007/12/22/client-side-mvc-with-jmvc-and-aspnet-mvc/#comments</comments>
		<pubDate>Sat, 22 Dec 2007 10:20:37 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
		
		<category><![CDATA[JSON]]></category>

		<category><![CDATA[MVC]]></category>

		<category><![CDATA[jMVC]]></category>

		<guid isPermaLink="false">http://blog.codeville.net/2007/12/22/client-side-mvc-with-jmvc-and-aspnet-mvc/</guid>
		<description><![CDATA[As you might expect, it&#8217;s pretty neat and simple to use jMVC with the new ASP.NET MVC framework. Since MVC coders already understand the core concept, and since I&#8217;m about to give you a handy helper assembly, it hardly takes any effort at all.
Download helper assembly &#124; Download demo project &#124; Browse source repository
A reminder
In [...]]]></description>
			<content:encoded><![CDATA[<p>As you might expect, it&#8217;s pretty neat and simple to use jMVC with the new ASP.NET MVC framework. Since MVC coders already understand the core concept, and since I&#8217;m about to give you a handy helper assembly, it hardly takes any effort at all.</p>
<p><a href="http://blog.codeville.net/blogfiles/2007/jMVC-forAspNetMvc/jMVCforAspNetMvc-v1.0.zip" target="_blank">Download helper assembly</a> | <a href="http://blog.codeville.net/blogfiles/2007/jMVC-forAspNetMvc/TestJmvcInMVC.zip" target="_blank">Download demo project</a> | <a href="http://jmvcnet.googlecode.com/svn/trunk/OtherPlatforms/ASP.NET%20MVC/" target="_blank">Browse source repository</a></p>
<h3>A reminder</h3>
<p>In case you&#8217;ve missed my <a href="http://blog.codeville.net/?s=jMVC">other posts about jMVC</a>, it&#8217;s a teeny-tiny Javascript library which brings the MVC coding experience into the browser. It doesn&#8217;t solve world hunger, but it does make it far easier to build UIs that change dynamically according to data entered or options chosen, without needing any calls to the server (that means you, AJAX). There&#8217;s a <a href="http://codeville.net/">demo site</a> and a <a href="http://www.codeproject.com/KB/scripting/jsonnet.aspx" target="_blank">tutorial on CodeProject.com</a>, both based around the ASP.NET flavour.</p>
<p>If you want to use it <a href="http://blog.codeville.net/2007/10/18/jmvcnet-neat-client-side-mvc-for-aspnet/">with ASP.NET</a>, or <a href="http://blog.codeville.net/2007/11/13/castle-monorail-meets-jmvc/">with Castle MonoRail</a>, you can have the convenience of strongly-typed .NET objects on the server databound (in and out) to a dynamic UI on the client. This post will show how to get the same convenience when using ASP.NET MVC.</p>
<h3>Installation</h3>
<p>1. Start a new MVC Web Application, or open an existing one.</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="235" alt="image" src="http://blog.codeville.net/wp-content/uploads/2007/12/image.png" width="565" border="0" /> </p>
<p>2. Download the <a href="http://blog.codeville.net/blogfiles/2007/jMVC-forAspNetMvc/jMVCforAspNetMvc-v1.0.zip" target="_blank">jMVC for ASP.NET MVC package</a>, or build it yourself from the <a href="http://code.google.com/p/jmvcnet">sources</a>. Copy the two DLLs somewhere accessible to your project, and add a reference to them.</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="464" alt="image" src="http://blog.codeville.net/wp-content/uploads/2007/12/image1.png" width="531" border="0" /> </p>
<p>3. In your web.config file, add a reference to the jMVCHelper namespace:</p>
<p>&#160;<img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="294" alt="image" src="http://blog.codeville.net/wp-content/uploads/2007/12/image2.png" width="383" border="0" /> </p>
<p>Well done, you&#8217;re ready to go!</p>
<h3>Usage</h3>
<p>I&#8217;ll copy the same Task List example as used on the <a href="http://www.codeproject.com/KB/scripting/jsonnet.aspx" target="_blank" rel="nofollow">CodeProject.com article</a>. We want to add to our MVC application a simple, fully client-side task list editor looking like this:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="405" alt="image" src="http://blog.codeville.net/wp-content/uploads/2007/12/image3.png" width="587" border="0" /> </p>
<p>First, go to the controller that&#8217;s going to provide the data. If you just made a new MVC application using the default template, you can use HomeController.cs, and edit it to look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">public</span> <span style="color: #0000FF;">class</span> HomeController : Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">private</span> <span style="color: #0000FF;">class</span> Task
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Name;
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">bool</span> IsCompleted = <span style="color: #0000FF;">false</span>;
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">bool</span> HasNotes = <span style="color: #0000FF;">false</span>;
        <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">string</span> Notes = <span style="color: #A31515;">&quot;&quot;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>ControllerAction<span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>            
        <span style="color: #008000;">// Supply some initial data to jMVC</span>
        <span style="color: #008000;">// You'd normally get it from a database, </span>
	<span style="color: #008000;">// rather than hard-coding it</span>
        ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;tasks&quot;</span><span style="color: #000000;">&#93;</span> = <span style="color: #0000FF;">new</span> List&lt;Task&gt;<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
            <span style="color: #0000FF;">new</span> Task <span style="color: #000000;">&#123;</span> Name = <span style="color: #A31515;">&quot;Feed fish&quot;</span>, IsCompleted = <span style="color: #0000FF;">true</span> <span style="color: #000000;">&#125;</span>, 
            <span style="color: #0000FF;">new</span> Task <span style="color: #000000;">&#123;</span> Name = <span style="color: #A31515;">&quot;Buy new digital SLR&quot;</span> <span style="color: #000000;">&#125;</span> 
        <span style="color: #000000;">&#125;</span>;
&nbsp;
        RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#91;</span>ControllerAction<span style="color: #000000;">&#93;</span>
    <span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> About<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">// Not really using this, but can leave it in place</span>
        RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;About&quot;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>So, we&#8217;ve defined a data structure for our Task objects, and assigned a List of them into the ViewData for the page.</p>
<p>Now, in the corresponding view (Index.aspx, in this case), you can insert the jMVC panel like so:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="105" alt="image" src="http://blog.codeville.net/wp-content/uploads/2007/12/image4.png" width="622" border="0" /> </p>
<p>If you run the application now, you&#8217;ll get a weird 404 error because it&#8217;s trying to load <strong>/Views/jMVC/tasks.jmvc</strong>, but you haven&#8217;t created this yet. Create a new blank text file at that location. This isn&#8217;t a tutorial on jMVC syntax (for that, see <a href="http://blog.codeville.net/2007/10/04/rich-javascript-mvc-user-interfaces-with-jmvc/">this guide</a>, or examine the <a href="http://codeville.net/" target="_blank">samples</a>), so just paste in the following:</p>

<div class="wp_syntax"><div class="code"><pre>&lt;% if(model.tasks.length == 0) { %&gt;
    &lt;p&gt;No tasks have been added.&lt;/p&gt;
&lt;% } else { %&gt;
    &lt;table border=&quot;1&quot; cellpadding=&quot;6&quot;&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th align=&quot;left&quot;&gt;Task&lt;/th&gt;
                &lt;th align=&quot;left&quot;&gt;Status&lt;/th&gt;
                &lt;th align=&quot;left&quot;&gt;&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;% for(var i = 0; i &lt; model.tasks.length; i++) { %&gt;
            &lt;tr&gt;
                &lt;td&gt;
                    &lt;span style='&lt;%= model.tasks[i].IsCompleted ? &quot;text-decoration:line-through&quot; : &quot;font-weight:bold&quot; %&gt;'&gt;
                        &lt;%= model.tasks[i].Name %&gt;
                    &lt;/span&gt;
                &lt;/td&gt;
                &lt;td&gt;
                    &lt;label&gt;
                        &lt;input type=&quot;checkbox&quot; onclick=&quot;&lt;%* function(i) { model.tasks[i].IsCompleted = this.checked } %&gt;&quot; 
                            &lt;%= model.tasks[i].IsCompleted ? &quot;checked&quot; : &quot;&quot; %&gt; /&gt;
                        Completed
                    &lt;/label&gt;
                    &lt;label&gt;
                        &lt;input type=&quot;checkbox&quot; onclick=&quot;&lt;%* function(i) { model.tasks[i].HasNotes = this.checked } %&gt;&quot; 
                            &lt;%= model.tasks[i].HasNotes ? &quot;checked&quot; : &quot;&quot; %&gt; /&gt;
                        Has notes
                    &lt;/label&gt;      
                    &lt;% if(model.tasks[i].HasNotes) { %&gt;          
                        &lt;div&gt;&lt;textarea onchange=&quot;&lt;%* function(i) { model.tasks[i].Notes = this.value; } %&gt;&quot;&gt;
                            &lt;%= model.tasks[i].Notes %&gt;&lt;/textarea&gt;&lt;/div&gt;
                    &lt;% } %&gt;
                &lt;/td&gt;
                &lt;td&gt;
                    &lt;a href=&quot;#&quot; onclick=&quot;&lt;%* function(i) { model.tasks.splice(i, 1); } %&gt;&quot;&quot;&gt;Delete&lt;/a&gt;
                &lt;/td&gt;
            &lt;/li&gt;
            &lt;/tr&gt;
        &lt;% } %&gt;
    &lt;/table&gt;
&lt;% } %&gt;
&nbsp;
Add new task: 
&lt;input type=&quot;text&quot; id=&quot;NewTaskName&quot; onkeypress=&quot;return event.keyCode != 13; /* don't submit form if ENTER is pressed */&quot;/&gt;
&lt;input type=&quot;button&quot; value=&quot;Add&quot; onclick=&quot;&lt;%* function() { addNewTask(model.tasks); } %&gt;&quot; /&gt;
&nbsp;
&lt;% 
    function addNewTask(taskList) {
        var taskName = document.getElementById(&quot;NewTaskName&quot;).value;
        if(taskName != &quot;&quot;)
            taskList[taskList.length] = { Name : taskName, Notes : &quot;&quot; };
    }
%&gt;</pre></div></div>

<p>I know that looks intimidating, but it&#8217;s more interesting than just printing &quot;Hello, world!&quot;. If you think about it for a minute, it&#8217;s similar syntax as you&#8217;d use in any ASP.NET MVC ViewPage, except in this case it&#8217;s going to be executed on the client, and Javascript event-handling is baked in. There are simpler examples on the <a href="http://codeville.net/" target="_blank">demo site</a>.</p>
<p>Soon I&#8217;m going to make the syntax cleaner by adding MVC-style view helper methods, so you&#8217;ll be able to write &lt;%= Html.TextBox(&#8230;) %&gt; etc., but for now you have to write all the HTML markup yourself.</p>
<h3>Getting data back on the server</h3>
<p>If you run the app now, you&#8217;ll be able to edit the task list. Whee! Isn&#8217;t that fun - no server communication at all! </p>
<p>Except there&#8217;s no way to post your work back to the server, so change your view to look like this:<br />
  <br />&#160;<img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="140" alt="image" src="http://blog.codeville.net/wp-content/uploads/2007/12/image5.png" width="620" border="0" /> </p>
<p><strong>Note: you need to add a reference to the <a href="http://asp.net/downloads/3.5-extensions/MVCToolkit.zip" target="_blank">MVC Toolkit</a> to use this syntax.</strong></p>
<p>Now we&#8217;ve added a proper HTML form with submit button. This means that jMVC is going to post a JSON string representing the edited data to the server with the name &quot;myJmvcPanel&quot;. To process that on the server, add a new action method to the controller:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #000000;">&#91;</span>ControllerAction<span style="color: #000000;">&#93;</span>
<span style="color: #0000FF;">public</span> <span style="color: #0000FF;">void</span> ReceiveData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">// Retrieve the edited data</span>
    List&lt;Task&gt; result = <span style="color: #0000FF;">this</span>.<span style="color: #0000FF;">ReadJsonFromRequest</span>&lt;List&lt;Task&gt;&gt;<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;myJmvcPanel&quot;</span>, <span style="color: #A31515;">&quot;tasks&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #008000;">// Do something useful with it, like save it to the database</span>
    <span style="color: #008000;">// In this case just prove we've got the updated data</span>
    ViewData<span style="color: #000000;">&#91;</span><span style="color: #A31515;">&quot;count&quot;</span><span style="color: #000000;">&#93;</span> = result.<span style="color: #0000FF;">Count</span>;
    RenderView<span style="color: #000000;">&#40;</span><span style="color: #A31515;">&quot;About&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>By the way, you&#8217;ll need to import the jMVCHelper namespace to use the ReadJsonFromRequest() helper method. Put this at the top of your controller file:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0000FF;">using</span> jMVCHelper;</pre></div></div>

<p>Hooray, we&#8217;re done. The user can add, edit and remove tasks in the browser with no client-server communication, then when they post the form, we get strongly-typed .NET objects to represent the submission.</p>
<p>If you couldn&#8217;t be bothered to type those things yourself, you can download the <a href="http://blog.codeville.net/blogfiles/2007/jMVC-forAspNetMvc/TestJmvcInMVC.zip" target="_blank">demo project</a> I prepared earlier.</p>
<img src="http://feeds.codeville.net/~r/SteveCodeville/~4/204591086" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.codeville.net/2007/12/22/client-side-mvc-with-jmvc-and-aspnet-mvc/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.codeville.net/2007/12/22/client-side-mvc-with-jmvc-and-aspnet-mvc/</feedburner:origLink></item>
	</channel>
</rss>
