<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" version="2.0">
  <channel>
    <title>ploeh blog - ASP.NET MVC</title>
    <link>http://blog.ploeh.dk/</link>
    <description>Mark Seemann's .NET blog</description>
    <language>en-us</language>
    <copyright>Mark Seemann</copyright>
    <lastBuildDate>Mon, 04 Jan 2010 20:53:24 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>mark@seemann.ms</managingEditor>
    <webMaster>mark@seemann.ms</webMaster>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=b4ca21d4-9046-4cff-bb74-3d0a50c958de</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=b4ca21d4-9046-4cff-bb74-3d0a50c958de</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a <a href="http://blog.ploeh.dk/2009/11/26/AnonymousDo.aspx">previous post</a> I
described how <a href="http://autofixture.codeplex.com/">AutoFixture</a>'s Do method
can let you invoke commands on your <a href="http://xunitpatterns.com/SUT.html">SUT</a> with <a href="http://xunitpatterns.com/Dummy%20Object.html">Dummy</a> values
for the parameters you don't care about.
</p>
        <p>
The Get method is the equivalent method you can use when the member you are invoking
returns a value. In other words: if you want to call a method on your SUT to get a
value, but you don't want the hassle of coming up with values you don't care about,
you can let the Get method supply those values for you.
</p>
        <p>
In today's example I will demonstrate a unit test that verifies the behavior of a
custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't
really matter. The point is that a ModelBinder must implement the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imodelbinder.aspx">IModelBinder</a> interface
that defines a single method:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">object</span> BindModel(<span style="color: #2b91af">ControllerContext</span> controllerContext,
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">ModelBindingContext</span> bindingContext);
</p>
        </div>
        <p>
In many cases we don't care about one or the other of these parameters, but we still
need to supply them when unit testing.
</p>
        <p>
The example is a bit more complex than some of my other sample code, but once in a
while I like to provide you with slightly more realistic AutoFixture examples. Still,
it's only 10 lines of code, but it looks like a lot more because I have wrapped several
of the lines so that the code is still readable on small screens.
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
[<span style="color: #2b91af">TestMethod</span>]
</p>
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> BindModelWillReturnCorrectResult()
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: green">// Fixture setup</span></p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> fixture = <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();
</p>
          <p style="margin: 0px">
    fixture.Customize&lt;<span style="color: #2b91af">ControllerContext</span>&gt;(ob
=&gt;
</p>
          <p style="margin: 0px">
        ob.OmitAutoProperties());
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> value = fixture.CreateAnonymous(<span style="color: #a31515">"Value"</span>);
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> bindingContext = <span style="color: blue">new</span><span style="color: #2b91af">ModelBindingContext</span>();
</p>
          <p style="margin: 0px">
    bindingContext.ValueProvider = 
</p>
          <p style="margin: 0px">
        <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: #2b91af">ValueProviderResult</span>&gt;();
</p>
          <p style="margin: 0px">
    bindingContext.ValueProvider[<span style="color: #a31515">"MyValue"</span>]
= 
</p>
          <p style="margin: 0px">
        <span style="color: blue">new</span><span style="color: #2b91af">ValueProviderResult</span>(value,
value, 
</p>
          <p style="margin: 0px">
            <span style="color: #2b91af">CultureInfo</span>.CurrentCulture);
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> expectedResult = 
</p>
          <p style="margin: 0px">
        <span style="color: blue">new</span><span style="color: blue">string</span>(value.Reverse().ToArray());
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> sut = fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyModelBinder</span>&gt;();
</p>
          <p style="margin: 0px">
    <span style="color: green">// Exercise system</span></p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> result = fixture.Get((<span style="color: #2b91af">ControllerContext</span> cc)
=&gt;
</p>
          <p style="margin: 0px">
        sut.BindModel(cc, bindingContext));
</p>
          <p style="margin: 0px">
    <span style="color: green">// Verify outcome</span></p>
          <p style="margin: 0px">
    <span style="color: #2b91af">Assert</span>.AreEqual(expectedResult,
result, <span style="color: #a31515">"BindModel"</span>);
</p>
          <p style="margin: 0px">
    <span style="color: green">// Teardown</span></p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
The first part simply creates the Fixture object and <a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx">customizes</a> it
to <a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx">disable
AutoProperties</a> for all ControllerContext instances (otherwise we would have to
set up a lot of <a href="http://xunitpatterns.com/Test%20Double.html">Test Doubles</a> for
such properties as HttpContext, RequestContext etc.).
</p>
        <p>
The next part of the test sets up a ModelBindingContext instance that will be used
to exercise the SUT. In this test case, the <em>bindingContext</em> parameter of the
BindModel method is important, so I explicitly set that up. On the other hand, I don't
care about the <em>controllerContext</em> parameter in this test case, so I ask the
Get method to take care of that for me:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">var</span> result = fixture.Get((<span style="color: #2b91af">ControllerContext</span> cc)
=&gt;
</p>
          <p style="margin: 0px">
    sut.BindModel(cc, bindingContext));
</p>
        </div>
        <p>
The Get method creates a Dummy value for the ControllerContext, whereas I can still
use the outer variable <em>bindingContext</em> to call the BindModel method. The return
value of the BindModel method is returned to the <em>result</em> variable by the Get
method.
</p>
        <p>
Like the Do methods, the Get methods are generic methods. The one invoked in this
example has this signature:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span> TResult Get&lt;T, TResult&gt;(<span style="color: #2b91af">Func</span>&lt;T,
TResult&gt; function);
</p>
        </div>
        <p>
There are also overloads that works with the versions of the Func delegate that takes
two, three and four parameters.
</p>
        <p>
As the Do methods, the Get methods are convenience methods that let you concentrate
on writing the test code you care about while it takes care of all the rest. You could
have written a slightly more complex version that didn't use Get but instead used
the CreateAnonymous method to create an Anonymous Variable for the ControllerContext,
but this way is slightly more succinct.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b4ca21d4-9046-4cff-bb74-3d0a50c958de" />
      </body>
      <title>Anonymous Get</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/04/AnonymousGet.aspx</link>
      <pubDate>Mon, 04 Jan 2010 20:53:24 GMT</pubDate>
      <description>&lt;p&gt;
In a &lt;a href="http://blog.ploeh.dk/2009/11/26/AnonymousDo.aspx"&gt;previous post&lt;/a&gt; I
described how &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;'s Do method
can let you invoke commands on your &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt; with &lt;a href="http://xunitpatterns.com/Dummy%20Object.html"&gt;Dummy&lt;/a&gt; values
for the parameters you don't care about.
&lt;/p&gt;
&lt;p&gt;
The Get method is the equivalent method you can use when the member you are invoking
returns a value. In other words: if you want to call a method on your SUT to get a
value, but you don't want the hassle of coming up with values you don't care about,
you can let the Get method supply those values for you.
&lt;/p&gt;
&lt;p&gt;
In today's example I will demonstrate a unit test that verifies the behavior of a
custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't
really matter. The point is that a ModelBinder must implement the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imodelbinder.aspx"&gt;IModelBinder&lt;/a&gt; interface
that defines a single method:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;object&lt;/span&gt; BindModel(&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; controllerContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ModelBindingContext&lt;/span&gt; bindingContext);
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
In many cases we don't care about one or the other of these parameters, but we still
need to supply them when unit testing.
&lt;/p&gt;
&lt;p&gt;
The example is a bit more complex than some of my other sample code, but once in a
while I like to provide you with slightly more realistic AutoFixture examples. Still,
it's only 10 lines of code, but it looks like a lot more because I have wrapped several
of the lines so that the code is still readable on small screens.
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; BindModelWillReturnCorrectResult()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Fixture setup&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fixture = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Customize&amp;lt;&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt;&amp;gt;(ob
=&amp;gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ob.OmitAutoProperties());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; value = fixture.CreateAnonymous(&lt;span style="color: #a31515"&gt;"Value"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; bindingContext = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ModelBindingContext&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; bindingContext.ValueProvider = 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;ValueProviderResult&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; bindingContext.ValueProvider[&lt;span style="color: #a31515"&gt;"MyValue"&lt;/span&gt;]
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ValueProviderResult&lt;/span&gt;(value,
value, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;CultureInfo&lt;/span&gt;.CurrentCulture);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; expectedResult = 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt;(value.Reverse().ToArray());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut = fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyModelBinder&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Exercise system&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; result = fixture.Get((&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; cc)
=&amp;gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.BindModel(cc, bindingContext));
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Verify outcome&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(expectedResult,
result, &lt;span style="color: #a31515"&gt;"BindModel"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Teardown&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
The first part simply creates the Fixture object and &lt;a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx"&gt;customizes&lt;/a&gt; it
to &lt;a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx"&gt;disable
AutoProperties&lt;/a&gt; for all ControllerContext instances (otherwise we would have to
set up a lot of &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test Doubles&lt;/a&gt; for
such properties as HttpContext, RequestContext etc.).
&lt;/p&gt;
&lt;p&gt;
The next part of the test sets up a ModelBindingContext instance that will be used
to exercise the SUT. In this test case, the &lt;em&gt;bindingContext&lt;/em&gt; parameter of the
BindModel method is important, so I explicitly set that up. On the other hand, I don't
care about the &lt;em&gt;controllerContext&lt;/em&gt; parameter in this test case, so I ask the
Get method to take care of that for me:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;var&lt;/span&gt; result = fixture.Get((&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; cc)
=&amp;gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.BindModel(cc, bindingContext));
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
The Get method creates a Dummy value for the ControllerContext, whereas I can still
use the outer variable &lt;em&gt;bindingContext&lt;/em&gt; to call the BindModel method. The return
value of the BindModel method is returned to the &lt;em&gt;result&lt;/em&gt; variable by the Get
method.
&lt;/p&gt;
&lt;p&gt;
Like the Do methods, the Get methods are generic methods. The one invoked in this
example has this signature:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; TResult Get&amp;lt;T, TResult&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,
TResult&amp;gt; function);
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
There are also overloads that works with the versions of the Func delegate that takes
two, three and four parameters.
&lt;/p&gt;
&lt;p&gt;
As the Do methods, the Get methods are convenience methods that let you concentrate
on writing the test code you care about while it takes care of all the rest. You could
have written a slightly more complex version that didn't use Get but instead used
the CreateAnonymous method to create an Anonymous Variable for the ControllerContext,
but this way is slightly more succinct.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b4ca21d4-9046-4cff-bb74-3d0a50c958de" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=ee8935b9-d418-4078-99e6-71eec380680b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ee8935b9-d418-4078-99e6-71eec380680b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my previous posts I discussed <a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx">how
to enable global error handling in ASP.NET MVC</a> and <a href="http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx">how
to inject a logging interface into the error handler</a>. In these posts, I simplified
things a bit to get my points across.
</p>
        <p>
In production we don't use a custom ErrorHandlingControllerFactory to configure all
Controllers with error handling, nor do we instantiate IExceptionFilters manually.
What I described was the Poor Man's Dependency Injection (DI) approach, which I find
most appropriate when describing DI concepts.
</p>
        <p>
However, we really use <a href="http://castleproject.org/container/index.html">Castle
Windsor</a> currently, so the wiring looks a bit different although it's still exactly
the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter
are any different than I have already described, but for completeness I wanted to
share a bit of our Windsor code.
</p>
        <p>
This is how we really wire our Controllers:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 container.Register(\cf3 AllTypes\par ??\cf0     .FromAssemblyContaining(representativeControllerType)\par ??    .BasedOn&lt;\cf3 Controller\cf0 &gt;()\par ??    .ConfigureFor&lt;\cf3 Controller\cf0 &gt;(reg =&gt; \par ??        reg.LifeStyle.PerWebRequest.ServiceOverrides(\par ??            \cf4 new\cf0  \{ ActionInvoker = \cf4 typeof\cf0 (\par ??                \cf3 ErrorHandlingControllerActionInvoker\cf0 )\par ??                .FullName \})));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">AllTypes</span></pre>
          <pre style="margin: 0px">    .FromAssemblyContaining(representativeControllerType)</pre>
          <pre style="margin: 0px">    .BasedOn&lt;<span style="color: #2b91af">Controller</span>&gt;()</pre>
          <pre style="margin: 0px">    .ConfigureFor&lt;<span style="color: #2b91af">Controller</span>&gt;(reg
=&gt; </pre>
          <pre style="margin: 0px">        reg.LifeStyle.PerWebRequest.ServiceOverrides(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span> {
ActionInvoker = <span style="color: blue">typeof</span>(</pre>
          <pre style="margin: 0px">                <span style="color: #2b91af">ErrorHandlingControllerActionInvoker</span>)</pre>
          <pre style="margin: 0px">                .FullName })));</pre>
        </div>
        <p>
Most of this statement simply instructs Windsor to scan all types in the specified
assembly for Controller implementations and register them. The interesting part is
the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining
that the ActionInvoker property should be wired up with an instance of the component
registered as ErrorHandlingControllerActionInvoker.
</p>
        <p>
Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance
we need to configure at least one of these as well. Instead of one, however, we have
two:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 container.Register(\cf3 Component\cf0 .For&lt;\cf3 IExceptionFilter\cf0 &gt;()\par ??    .ImplementedBy&lt;\cf3 LoggingExceptionFilter\cf0 &gt;());\par ??container.Register(\cf3 Component\cf0 .For&lt;\cf3 IExceptionFilter\cf0 &gt;()\par ??    .ImplementedBy&lt;\cf3 HandleErrorAttribute\cf0 &gt;());}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IExceptionFilter</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">LoggingExceptionFilter</span>&gt;());</pre>
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IExceptionFilter</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">HandleErrorAttribute</span>&gt;());</pre>
        </div>
        <p>
This is Windsor's elegant way of registering <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorators</a>:
you simply register the Decorator before the decorated type, and it'll Auto-Wire everything
for you.
</p>
        <p>
Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from
the <a href="http://www.codeplex.com/MVCContrib">MVC Contrib</a> project.
</p>
        <p>
To reiterate: You don't have to use Castle Windsor to enable global error handling
or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous
posts, or you can use some other DI Container. The purpose of this post was simply
to demonstrate one way to take it to the next level.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ee8935b9-d418-4078-99e6-71eec380680b" />
      </body>
      <title>Wiring ASP.NET MVC Error Handling with Castle Windsor</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/14/WiringASPNETMVCErrorHandlingWithCastleWindsor.aspx</link>
      <pubDate>Mon, 14 Dec 2009 06:59:32 GMT</pubDate>
      <description>&lt;p&gt;
In my previous posts I discussed &lt;a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx"&gt;how
to enable global error handling in ASP.NET MVC&lt;/a&gt; and &lt;a href="http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx"&gt;how
to inject a logging interface into the error handler&lt;/a&gt;. In these posts, I simplified
things a bit to get my points across.
&lt;/p&gt;
&lt;p&gt;
In production we don't use a custom ErrorHandlingControllerFactory to configure all
Controllers with error handling, nor do we instantiate IExceptionFilters manually.
What I described was the Poor Man's Dependency Injection (DI) approach, which I find
most appropriate when describing DI concepts.
&lt;/p&gt;
&lt;p&gt;
However, we really use &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt; currently, so the wiring looks a bit different although it's still exactly
the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter
are any different than I have already described, but for completeness I wanted to
share a bit of our Windsor code.
&lt;/p&gt;
&lt;p&gt;
This is how we really wire our Controllers:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 container.Register(\cf3 AllTypes\par ??\cf0     .FromAssemblyContaining(representativeControllerType)\par ??    .BasedOn&amp;lt;\cf3 Controller\cf0 &amp;gt;()\par ??    .ConfigureFor&amp;lt;\cf3 Controller\cf0 &amp;gt;(reg =&amp;gt; \par ??        reg.LifeStyle.PerWebRequest.ServiceOverrides(\par ??            \cf4 new\cf0  \{ ActionInvoker = \cf4 typeof\cf0 (\par ??                \cf3 ErrorHandlingControllerActionInvoker\cf0 )\par ??                .FullName \})));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;AllTypes&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .FromAssemblyContaining(representativeControllerType)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .BasedOn&amp;lt;&lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ConfigureFor&amp;lt;&lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&amp;gt;(reg
=&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; reg.LifeStyle.PerWebRequest.ServiceOverrides(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; {
ActionInvoker = &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerActionInvoker&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .FullName })));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Most of this statement simply instructs Windsor to scan all types in the specified
assembly for Controller implementations and register them. The interesting part is
the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining
that the ActionInvoker property should be wired up with an instance of the component
registered as ErrorHandlingControllerActionInvoker.
&lt;/p&gt;
&lt;p&gt;
Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance
we need to configure at least one of these as well. Instead of one, however, we have
two:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 container.Register(\cf3 Component\cf0 .For&amp;lt;\cf3 IExceptionFilter\cf0 &amp;gt;()\par ??    .ImplementedBy&amp;lt;\cf3 LoggingExceptionFilter\cf0 &amp;gt;());\par ??container.Register(\cf3 Component\cf0 .For&amp;lt;\cf3 IExceptionFilter\cf0 &amp;gt;()\par ??    .ImplementedBy&amp;lt;\cf3 HandleErrorAttribute\cf0 &amp;gt;());}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;&amp;gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is Windsor's elegant way of registering &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorators&lt;/a&gt;:
you simply register the Decorator before the decorated type, and it'll Auto-Wire everything
for you.
&lt;/p&gt;
&lt;p&gt;
Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from
the &lt;a href="http://www.codeplex.com/MVCContrib"&gt;MVC Contrib&lt;/a&gt; project.
&lt;/p&gt;
&lt;p&gt;
To reiterate: You don't have to use Castle Windsor to enable global error handling
or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous
posts, or you can use some other DI Container. The purpose of this post was simply
to demonstrate one way to take it to the next level.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ee8935b9-d418-4078-99e6-71eec380680b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=be8504e1-b78f-4246-9338-717f7d0529b5</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=be8504e1-b78f-4246-9338-717f7d0529b5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a previous post I described <a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx">how
to enable global error handling in ASP.NET MVC applications</a>. Although I spent
some time talking about the importance of DRY, another major motivation for me was
to enable Dependency Injection (DI) with exception handling so that I could log stack
traces before letting ASP.NET MVC handle the exception.
</p>
        <p>
With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter
implementation. As an example I used HandleErrorAttribute, but obviously that doesn't
log anything. Once again, it would be tempting to derive from HandleErrorAttribute
and override its OnException method, but staying true to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> as well as the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/Closed
Principle</a> I rather prefer a <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LoggingExceptionFilter\cf0  : \cf4 IExceptionFilter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IExceptionFilter\cf0  filter;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 ILogWriter\cf0  logWriter;\par ??\par ??    \cf1 public\cf0  LoggingExceptionFilter(\cf4 IExceptionFilter\cf0  filter,\par ??        \cf4 ILogWriter\cf0  logWriter)\par ??    \{\par ??        \cf1 if\cf0  (filter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "filter"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (logWriter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "logWriter"\cf0 );\par ??        \}        \par ??    \par ??        \cf1 this\cf0 .filter = filter;\par ??        \cf1 this\cf0 .logWriter = logWriter;\par ??    \}\par ??\par ??\cf1     #region\cf0  IExceptionFilter Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  OnException(\cf4 ExceptionContext\cf0  filterContext)\par ??    \{\par ??        \cf1 this\cf0 .logWriter.WriteError(filterContext.Exception);\par ??        \cf1 this\cf0 .filter.OnException(filterContext);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">LoggingExceptionFilter</span> : <span style="color: #2b91af">IExceptionFilter</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IExceptionFilter</span> filter;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">ILogWriter</span> logWriter;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> LoggingExceptionFilter(<span style="color: #2b91af">IExceptionFilter</span> filter,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ILogWriter</span> logWriter)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (filter
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (logWriter
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"logWriter"</span>);</pre>
          <pre style="margin: 0px">        }        </pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.filter
= filter;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.logWriter
= logWriter;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IExceptionFilter Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> OnException(<span style="color: #2b91af">ExceptionContext</span> filterContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.logWriter.WriteError(filterContext.Exception);</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.filter.OnException(filterContext);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The LoggingExceptionFilter shown above is unabridged production code. This is all
it takes to bridge the gap between IExceptionFilter and some ILogWriter interface
(replace with the logging framework of your choice). Notice how it simply logs the
error and then passes on exception handling to the decorated IExceptionFilter.
</p>
        <p>
Currently we use HandleErrorAttribute as the decorated filter so that behavior stays
as expected.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 c.ActionInvoker = \par ??    \cf3 new\cf0  \cf4 ErrorHandlingControllerActionInvoker\cf0 (\par ??        \cf3 new\cf0  \cf4 LoggingExceptionFilter\cf0 (\par ??            \cf3 new\cf0  \cf4 HandleErrorAttribute\cf0 (), logWriter));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">c.ActionInvoker = </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingControllerActionInvoker</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">LoggingExceptionFilter</span>(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">HandleErrorAttribute</span>(),
logWriter));</pre>
        </div>
        <p>
This is not too different from before, except that a LoggingExceptionFilter now decorates
the HandleErrorAttribute instance.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be8504e1-b78f-4246-9338-717f7d0529b5" />
      </body>
      <title>LoggingExceptionFilter</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx</link>
      <pubDate>Mon, 07 Dec 2009 06:20:27 GMT</pubDate>
      <description>&lt;p&gt;
In a previous post I described &lt;a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx"&gt;how
to enable global error handling in ASP.NET MVC applications&lt;/a&gt;. Although I spent
some time talking about the importance of DRY, another major motivation for me was
to enable Dependency Injection (DI) with exception handling so that I could log stack
traces before letting ASP.NET MVC handle the exception.
&lt;/p&gt;
&lt;p&gt;
With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter
implementation. As an example I used HandleErrorAttribute, but obviously that doesn't
log anything. Once again, it would be tempting to derive from HandleErrorAttribute
and override its OnException method, but staying true to the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt; as well as the &lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open/Closed
Principle&lt;/a&gt; I rather prefer a &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorator&lt;/a&gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LoggingExceptionFilter\cf0  : \cf4 IExceptionFilter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IExceptionFilter\cf0  filter;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 ILogWriter\cf0  logWriter;\par ??\par ??    \cf1 public\cf0  LoggingExceptionFilter(\cf4 IExceptionFilter\cf0  filter,\par ??        \cf4 ILogWriter\cf0  logWriter)\par ??    \{\par ??        \cf1 if\cf0  (filter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "filter"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (logWriter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "logWriter"\cf0 );\par ??        \}        \par ??    \par ??        \cf1 this\cf0 .filter = filter;\par ??        \cf1 this\cf0 .logWriter = logWriter;\par ??    \}\par ??\par ??\cf1     #region\cf0  IExceptionFilter Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  OnException(\cf4 ExceptionContext\cf0  filterContext)\par ??    \{\par ??        \cf1 this\cf0 .logWriter.WriteError(filterContext.Exception);\par ??        \cf1 this\cf0 .filter.OnException(filterContext);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ILogWriter&lt;/span&gt; logWriter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; LoggingExceptionFilter(&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ILogWriter&lt;/span&gt; logWriter)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (filter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"filter"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (logWriter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"logWriter"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter
= filter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.logWriter
= logWriter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IExceptionFilter Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; OnException(&lt;span style="color: #2b91af"&gt;ExceptionContext&lt;/span&gt; filterContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.logWriter.WriteError(filterContext.Exception);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter.OnException(filterContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The LoggingExceptionFilter shown above is unabridged production code. This is all
it takes to bridge the gap between IExceptionFilter and some ILogWriter interface
(replace with the logging framework of your choice). Notice how it simply logs the
error and then passes on exception handling to the decorated IExceptionFilter.
&lt;/p&gt;
&lt;p&gt;
Currently we use HandleErrorAttribute as the decorated filter so that behavior stays
as expected.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 c.ActionInvoker = \par ??    \cf3 new\cf0  \cf4 ErrorHandlingControllerActionInvoker\cf0 (\par ??        \cf3 new\cf0  \cf4 LoggingExceptionFilter\cf0 (\par ??            \cf3 new\cf0  \cf4 HandleErrorAttribute\cf0 (), logWriter));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;c.ActionInvoker = &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerActionInvoker&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;(),
logWriter));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is not too different from before, except that a LoggingExceptionFilter now decorates
the HandleErrorAttribute instance.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be8504e1-b78f-4246-9338-717f7d0529b5" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=1b080ce4-b5e9-4332-80dc-a362a0cc083d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=1b080ce4-b5e9-4332-80dc-a362a0cc083d</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
ASP.NET MVC comes with an error-handling feature that enables you to show nice error
Views to your users instead of the dreaded Yellow Screen of Death. The most prominently
described technique involves attributing either you Controller or a single Controller
action, like we see in the AccountController created by the Visual Studio project
template.
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
[<span style="color: #2b91af">HandleError</span>]
</p>
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">AccountController</span> : <span style="color: #2b91af">Controller</span> {
}
</p>
        </div>
        <p>
That sure is easy, but I don't like it for a number of reasons:
</p>
        <ul>
          <li>
Even though you can derive from HandleErrorAttribute, it's impossible to inject any
dependencies into Attributes because they must be fully constructed at compile-time.
That makes it really difficult to log errors to an interface. 
</li>
          <li>
It violates the DRY principle. Although it can be applied at the Controller level,
I still must remember to attribute all of my Controllers with the HandleErrorAttribute.</li>
        </ul>
        <p>
Another approach is to override Controller.OnException. That solves the DI problem,
but not the DRY problem.
</p>
        <p>
Attentive readers may now point out that I can define a base Controller that implements
the proper error handling, and require that all my Controllers derive from this base
Controller, but that doesn't satisfy me:
</p>
        <p>
First of all, it still violates the DRY principle. Whether I have to remember to apply
a [HandleError] attribute or derive from a : MyBaseController amounts to the same
thing. I (and all my team members) have to remember this always. It's unnecessary
project friction.
</p>
        <p>
The second thing that bugs me about this approach is that I really do <em>favor composition
over inheritance</em>. Error handling is a <em>cross-cutting concern</em>, so why
should all my Controllers have to derive from a base controller to enable this? That
is absurd.
</p>
        <p>
Fortunately, ASP.NET MVC offers a third way.
</p>
        <p>
The key lies in the Controller base class and how it deals with IExceptionFilters
(which HandleErrorAttribute implements). When a Controller action is invoked, this
actually happens through an IActionInvoker. The default ControllerActionInvoker is
responsible for gathering the list of IExceptionFilters, so the first thing we can
do is to derive from that and override its GetFilters method:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ErrorHandlingActionInvoker</span> :
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">ControllerActionInvoker</span></p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IExceptionFilter</span> filter;
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span> ErrorHandlingActionInvoker(
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">IExceptionFilter</span> filter)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (filter
== <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.filter
= filter;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: #2b91af">FilterInfo</span> GetFilters(
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">ControllerContext</span> controllerContext,
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">ActionDescriptor</span> actionDescriptor)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> filterInfo
= 
</p>
          <p style="margin: 0px">
            <span style="color: blue">base</span>.GetFilters(controllerContext, 
</p>
          <p style="margin: 0px">
            actionDescriptor);
</p>
          <p style="margin: 0px">
        filterInfo.ExceptionFilters.Add(<span style="color: blue">this</span>.filter);
</p>
          <p style="margin: 0px">
        <span style="color: blue">return</span> filterInfo;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not
tightly binding it to any particular implementation – it will work with any IExceptionFilter
we give it, so it simply serves the purpose of adding the filter at the right stage
so that it can deal with otherwise unhandled exceptions. It's pure infrastructure
code.
</p>
        <p>
Notice that I first invoke base.GetFilters and then add the injected filter to the
returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to
attempt to deal with the error first.
</p>
        <p>
This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every
Controller in the application. This can be done using a custom ControllerFactory:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ErrorHandlingControllerFactory</span> : 
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">DefaultControllerFactory</span></p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span><span style="color: blue">override</span><span style="color: #2b91af">IController</span> CreateController(
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">RequestContext</span> requestContext,
</p>
          <p style="margin: 0px">
        <span style="color: blue">string</span> controllerName)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> controller
= 
</p>
          <p style="margin: 0px">
            <span style="color: blue">base</span>.CreateController(requestContext,
</p>
          <p style="margin: 0px">
            controllerName);
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> c
= controller <span style="color: blue">as</span><span style="color: #2b91af">Controller</span>;
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (c
!= <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            c.ActionInvoker
= 
</p>
          <p style="margin: 0px">
                <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingActionInvoker</span>(
</p>
          <p style="margin: 0px">
                    <span style="color: blue">new</span><span style="color: #2b91af">HandleErrorAttribute</span>());
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">return</span> controller;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
Notice that I'm simply deriving from the DefaultControllerFactory and overriding the
CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.
</p>
        <p>
In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker
instance. This seems weird, but it's the HandleErrorAttribute that implements the
default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter,
it works like a charm.
</p>
        <p>
The only thing left to do is to wire up the custom ErrorHandlingControllerFactory
in global.asax like this:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: #2b91af">ControllerBuilder</span>.Current.SetControllerFactory(
</p>
          <p style="margin: 0px">
    <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingControllerFactory</span>());
</p>
        </div>
        <p>
Now any Controller action that throws an exception is gracefully handled by the injected
IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters,
any normal [HandleError] attribute and Controller.OnException override gets a chance
to deal with the exception first, so this doesn't even change behavior of existing
code.
</p>
        <p>
If you are trying this out on your own development machine, remember that you must
modify your web.config like so:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">customErrors</span>
            <span style="color: blue">
            </span>
            <span style="color: red">mode</span>
            <span style="color: blue">=</span>"<span style="color: blue">On</span>"<span style="color: blue"> /&gt;</span></p>
        </div>
        <p>
If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on
your local box.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1b080ce4-b5e9-4332-80dc-a362a0cc083d" />
      </body>
      <title>Global Error Handling in ASP.NET MVC</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx</link>
      <pubDate>Tue, 01 Dec 2009 06:37:01 GMT</pubDate>
      <description>&lt;p&gt;
ASP.NET MVC comes with an error-handling feature that enables you to show nice error
Views to your users instead of the dreaded Yellow Screen of Death. The most prominently
described technique involves attributing either you Controller or a single Controller
action, like we see in the AccountController created by the Visual Studio project
template.
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
[&lt;span style="color: #2b91af"&gt;HandleError&lt;/span&gt;]
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;AccountController&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt; {
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
That sure is easy, but I don't like it for a number of reasons:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Even though you can derive from HandleErrorAttribute, it's impossible to inject any
dependencies into Attributes because they must be fully constructed at compile-time.
That makes it really difficult to log errors to an interface. 
&lt;li&gt;
It violates the DRY principle. Although it can be applied at the Controller level,
I still must remember to attribute all of my Controllers with the HandleErrorAttribute.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Another approach is to override Controller.OnException. That solves the DI problem,
but not the DRY problem.
&lt;/p&gt;
&lt;p&gt;
Attentive readers may now point out that I can define a base Controller that implements
the proper error handling, and require that all my Controllers derive from this base
Controller, but that doesn't satisfy me:
&lt;/p&gt;
&lt;p&gt;
First of all, it still violates the DRY principle. Whether I have to remember to apply
a [HandleError] attribute or derive from a : MyBaseController amounts to the same
thing. I (and all my team members) have to remember this always. It's unnecessary
project friction.
&lt;/p&gt;
&lt;p&gt;
The second thing that bugs me about this approach is that I really do &lt;em&gt;favor composition
over inheritance&lt;/em&gt;. Error handling is a &lt;em&gt;cross-cutting concern&lt;/em&gt;, so why
should all my Controllers have to derive from a base controller to enable this? That
is absurd.
&lt;/p&gt;
&lt;p&gt;
Fortunately, ASP.NET MVC offers a third way.
&lt;/p&gt;
&lt;p&gt;
The key lies in the Controller base class and how it deals with IExceptionFilters
(which HandleErrorAttribute implements). When a Controller action is invoked, this
actually happens through an IActionInvoker. The default ControllerActionInvoker is
responsible for gathering the list of IExceptionFilters, so the first thing we can
do is to derive from that and override its GetFilters method:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingActionInvoker&lt;/span&gt; :
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ControllerActionInvoker&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; ErrorHandlingActionInvoker(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (filter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"filter"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter
= filter;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;protected&lt;/span&gt; &lt;span style="color: blue"&gt;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FilterInfo&lt;/span&gt; GetFilters(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; controllerContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ActionDescriptor&lt;/span&gt; actionDescriptor)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; filterInfo
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;base&lt;/span&gt;.GetFilters(controllerContext, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; actionDescriptor);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; filterInfo.ExceptionFilters.Add(&lt;span style="color: blue"&gt;this&lt;/span&gt;.filter);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; filterInfo;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not
tightly binding it to any particular implementation – it will work with any IExceptionFilter
we give it, so it simply serves the purpose of adding the filter at the right stage
so that it can deal with otherwise unhandled exceptions. It's pure infrastructure
code.
&lt;/p&gt;
&lt;p&gt;
Notice that I first invoke base.GetFilters and then add the injected filter to the
returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to
attempt to deal with the error first.
&lt;/p&gt;
&lt;p&gt;
This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every
Controller in the application. This can be done using a custom ControllerFactory:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerFactory&lt;/span&gt; : 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DefaultControllerFactory&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IController&lt;/span&gt; CreateController(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;RequestContext&lt;/span&gt; requestContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;string&lt;/span&gt; controllerName)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; controller
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;base&lt;/span&gt;.CreateController(requestContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; controllerName);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; c
= controller &lt;span style="color: blue"&gt;as&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (c
!= &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c.ActionInvoker
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingActionInvoker&lt;/span&gt;(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; controller;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that I'm simply deriving from the DefaultControllerFactory and overriding the
CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.
&lt;/p&gt;
&lt;p&gt;
In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker
instance. This seems weird, but it's the HandleErrorAttribute that implements the
default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter,
it works like a charm.
&lt;/p&gt;
&lt;p&gt;
The only thing left to do is to wire up the custom ErrorHandlingControllerFactory
in global.asax like this:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: #2b91af"&gt;ControllerBuilder&lt;/span&gt;.Current.SetControllerFactory(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerFactory&lt;/span&gt;());
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Now any Controller action that throws an exception is gracefully handled by the injected
IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters,
any normal [HandleError] attribute and Controller.OnException override gets a chance
to deal with the exception first, so this doesn't even change behavior of existing
code.
&lt;/p&gt;
&lt;p&gt;
If you are trying this out on your own development machine, remember that you must
modify your web.config like so:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;customErrors&lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;"&lt;span style="color: blue"&gt;On&lt;/span&gt;"&lt;span style="color: blue"&gt; /&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on
your local box.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1b080ce4-b5e9-4332-80dc-a362a0cc083d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</comments>
      <category>ASP.NET MVC</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=4276a194-a567-47ab-80b3-23c2813537f3</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=4276a194-a567-47ab-80b3-23c2813537f3</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When using <a href="http://castleproject.org/container/index.html">Castle Windsor</a> in
web applications you would want to register many of your components with a lifestyle
that is associated with a single request. This is the purpose of the PerWebRequest
lifestyle.
</p>
        <p>
If you try that with ASP.NET MVC on IIS7, you are likely to receive the following
error message:
</p>
        <blockquote>
          <p>
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule 
<br />
Add '&lt;add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" /&gt;' to the &lt;httpModules&gt; section on your web.config.
</p>
        </blockquote>
        <p>
Unfortunately, following the instructions in the error message doesn't help. There's
a <a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e/1c33a54539f8abf7">discussion
about this issue</a> on the Castle Project Users forum, but the gist of it is that
if you don't need to <em>resolve</em> components during application startup, this
shouldn't be an issue, and indeed it isn't – it seems to be something else. 
</p>
        <p>
In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules
instead of configuration/system.web/httpModules. 
</p>
        <p>
Although I haven't had the opportunity to dive into the technical details to understand <em>why</em> this
works, this seems to solve the problem on both Windows Vista and Windows Server 2008.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4276a194-a567-47ab-80b3-23c2813537f3" />
      </body>
      <title>Using Castle Windsor's PerWebRequest lifestyle with ASP.NET MVC on IIS7</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/17/UsingCastleWindsorsPerWebRequestLifestyleWithASPNETMVCOnIIS7.aspx</link>
      <pubDate>Tue, 17 Nov 2009 12:44:37 GMT</pubDate>
      <description>&lt;p&gt;
When using &lt;a href="http://castleproject.org/container/index.html"&gt;Castle Windsor&lt;/a&gt; in
web applications you would want to register many of your components with a lifestyle
that is associated with a single request. This is the purpose of the PerWebRequest
lifestyle.
&lt;/p&gt;
&lt;p&gt;
If you try that with ASP.NET MVC on IIS7, you are likely to receive the following
error message:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule 
&lt;br&gt;
Add '&amp;lt;add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" /&amp;gt;' to the &amp;lt;httpModules&amp;gt; section on your web.config.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Unfortunately, following the instructions in the error message doesn't help. There's
a &lt;a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e/1c33a54539f8abf7"&gt;discussion
about this issue&lt;/a&gt; on the Castle Project Users forum, but the gist of it is that
if you don't need to &lt;em&gt;resolve&lt;/em&gt; components during application startup, this
shouldn't be an issue, and indeed it isn't – it seems to be something else. 
&lt;p&gt;
In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules
instead of configuration/system.web/httpModules. 
&lt;p&gt;
Although I haven't had the opportunity to dive into the technical details to understand &lt;em&gt;why&lt;/em&gt; this
works, this seems to solve the problem on both Windows Vista and Windows Server 2008.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4276a194-a567-47ab-80b3-23c2813537f3" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=73a82937-3edf-4e01-ae35-273a93d68160</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=73a82937-3edf-4e01-ae35-273a93d68160</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel
and I recently had that problem and we couldn't find any guidance on this topic, so
now that we have a solution, I thought I'd share it.
</p>
        <p>
The problem is simple: We needed a link that invoked some server side code and updated
the text of the link itself based on the result of the operation. Here is a simplified
example:
</p>
        <p>
          <a href="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_2.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_thumb.png" width="267" height="75" />
          </a>
        </p>
        <p>
Each time you click the link, it should invoke a Controller Action and return a new
number that should appear as the link text.
</p>
        <p>
This is pretty simple to implement once you know how. The first thing to realize is
that the link and all the AJAX stuff must be placed in a user control. The only thing
that needs to go into the containing page is the containing element itself:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &lt;\cf3 h2\cf1 &gt;\cf0 Self-updating AJAX link\cf1 &lt;/\cf3 h2\cf1 &gt;\par ??\cf0 Click the link to update the number:\par ??\cf1 &lt;\cf3 span\cf0  \cf5 id\cf1 ="thespan"&gt;\par ??\cf0     \cb6\highlight6 &lt;%\cb0\highlight0  \cf1 this\cf0 .Html.RenderPartial(\cf3 "NumberAjaxUserControl"\cf0 ); \cb6\highlight6 %&gt;\par ??\cf1\cb0\highlight0 &lt;/\cf3 span\cf1 &gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">h2</span>
            <span style="color: blue">&gt;</span>Self-updating
AJAX link<span style="color: blue">&lt;/</span><span style="color: #a31515">h2</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">Click the link to update the number:</pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">span</span>
            <span style="color: red">id</span>
            <span style="color: blue">="thespan"&gt;</span>
          </pre>
          <pre style="margin: 0px">    <span style="background: #ffee62">&lt;%</span><span style="color: blue">this</span>.Html.RenderPartial(<span style="color: #a31515">"NumberAjaxUserControl"</span>); <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">span</span>
            <span style="color: blue">&gt;</span>
          </pre>
        </div>
        <p>
Notice the <em>id</em> of the span element – this same <em>id</em> will be referenced
from the user control.
</p>
        <p>
To bootstrap this view, the Controller Action for the page contains code that assigns
an initial value to the number (in this case <em>1</em>):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 ActionResult\cf0  Index()\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = 1.ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .View();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">ActionResult</span> Index()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>]
= 1.ToString();</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span><span style="color: blue">this</span>.View();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
To keep the example simple, I simply add the number to the ViewData dictionary, but
in any production implementation, I would opt to use a strongly typed ViewModel instead.
</p>
        <p>
The NumberAjaxUserControl itself only contains the definition of the AJAX link:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red43\green145\blue175;}??\fs20 \cb2\highlight2 &lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Control\cf0  \cf6 Language\cf3 ="C#"\cf0  \cf6 Inherits\cf3 ="System.Web.Mvc.ViewUserControl"\cf0  \cb2\highlight2 %&gt;\par ??&lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Import\cf0  \cf6 Namespace\cf3 ="System.Web.Mvc.Ajax"\cf0  \cb2\highlight2 %&gt;\par ??&lt;%\cf3\cb0\highlight0 =\cf0  \cf3 this\cf0 .Ajax.ActionLink((\cf3 string\cf0 )\cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ],\par ??    \cf5 "GetNext"\cf0 ,\par ??    \cf3 new\cf0  \{ number = \cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ] \}, \par ??    \cf3 new\cf0  \cf7 AjaxOptions\cf0  \{ UpdateTargetId = \cf5 "thespan"\cf0  \})\cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">@</span>
            <span style="color: #a31515">Control</span>
            <span style="color: red">Language</span>
            <span style="color: blue">="C#"</span>
            <span style="color: red">Inherits</span>
            <span style="color: blue">="System.Web.Mvc.ViewUserControl"</span>
            <span style="background: #ffee62">%&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">@</span>
            <span style="color: #a31515">Import</span>
            <span style="color: red">Namespace</span>
            <span style="color: blue">="System.Web.Mvc.Ajax"</span>
            <span style="background: #ffee62">%&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">=</span>
            <span style="color: blue">this</span>.Ajax.ActionLink((<span style="color: blue">string</span>)<span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>],</pre>
          <pre style="margin: 0px">    <span style="color: #a31515">"GetNext"</span>,</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span> {
number = <span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>]
}, </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">AjaxOptions</span> {
UpdateTargetId = <span style="color: #a31515">"thespan"</span> })<span style="background: #ffee62">%&gt;</span></pre>
        </div>
        <p>
The first parameter to the ActionLink method is simply the current number to render
as the link text. Since I'm using the untyped ViewData dictionary for this example,
I need to cast it to a string.
</p>
        <p>
The next parameter ("GetNext") indicates the Controller Action to invoke when the
link is clicked – I will cover that shortly.
</p>
        <p>
The third parameter is a Route Value that specifies that the parameter <em>number</em> with
the correct value will be supplied to the GetNext Controller Action. It uses the number
stored in ViewData.
</p>
        <p>
The last parameter indicates the <em>id</em> of the element to update. Recall from
before that this name was "thespan".
</p>
        <p>
The only missing piece now is the GetNext Controller Action:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 PartialViewResult\cf0  GetNext(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = (number + 1).ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .PartialView(\cf5 "NumberAjaxUserControl"\cf0 );\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">PartialViewResult</span> GetNext(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>]
= (number + 1).ToString();</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span><span style="color: blue">this</span>.PartialView(<span style="color: #a31515">"NumberAjaxUserControl"</span>);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this example I simply chose to increment the number by one, but I'm sure you can
imagine that this method could just as well perform a database lookup or something
similar.
</p>
        <p>
Notice that the method returns a PartialViewResult that uses the same user control
that I used to bootstrap the <em>thespan</em> element. This means that every time
the link is clicked, the GetNext method is updated, and the exact same user control
is used to render the content that dynamically replaces the original content of the
element.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=73a82937-3edf-4e01-ae35-273a93d68160" />
      </body>
      <title>Self-updating AJAX links with ASP.NET MVC</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</guid>
      <link>http://blog.ploeh.dk/2009/09/07/SelfupdatingAJAXLinksWithASPNETMVC.aspx</link>
      <pubDate>Mon, 07 Sep 2009 18:14:39 GMT</pubDate>
      <description>&lt;p&gt;
How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel
and I recently had that problem and we couldn't find any guidance on this topic, so
now that we have a solution, I thought I'd share it.
&lt;/p&gt;
&lt;p&gt;
The problem is simple: We needed a link that invoked some server side code and updated
the text of the link itself based on the result of the operation. Here is a simplified
example:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_2.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_thumb.png" width="267" height="75"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Each time you click the link, it should invoke a Controller Action and return a new
number that should appear as the link text.
&lt;/p&gt;
&lt;p&gt;
This is pretty simple to implement once you know how. The first thing to realize is
that the link and all the AJAX stuff must be placed in a user control. The only thing
that needs to go into the containing page is the containing element itself:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &amp;lt;\cf3 h2\cf1 &amp;gt;\cf0 Self-updating AJAX link\cf1 &amp;lt;/\cf3 h2\cf1 &amp;gt;\par ??\cf0 Click the link to update the number:\par ??\cf1 &amp;lt;\cf3 span\cf0  \cf5 id\cf1 ="thespan"&amp;gt;\par ??\cf0     \cb6\highlight6 &amp;lt;%\cb0\highlight0  \cf1 this\cf0 .Html.RenderPartial(\cf3 "NumberAjaxUserControl"\cf0 ); \cb6\highlight6 %&amp;gt;\par ??\cf1\cb0\highlight0 &amp;lt;/\cf3 span\cf1 &amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;h2&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;Self-updating
AJAX link&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;h2&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;Click the link to update the number:&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;span&lt;/span&gt; &lt;span style="color: red"&gt;id&lt;/span&gt;&lt;span style="color: blue"&gt;="thespan"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Html.RenderPartial(&lt;span style="color: #a31515"&gt;"NumberAjaxUserControl"&lt;/span&gt;); &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;span&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice the &lt;em&gt;id&lt;/em&gt; of the span element – this same &lt;em&gt;id&lt;/em&gt; will be referenced
from the user control.
&lt;/p&gt;
&lt;p&gt;
To bootstrap this view, the Controller Action for the page contains code that assigns
an initial value to the number (in this case &lt;em&gt;1&lt;/em&gt;):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 ActionResult\cf0  Index()\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = 1.ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .View();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt; Index()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;]
= 1.ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.View();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
To keep the example simple, I simply add the number to the ViewData dictionary, but
in any production implementation, I would opt to use a strongly typed ViewModel instead.
&lt;/p&gt;
&lt;p&gt;
The NumberAjaxUserControl itself only contains the definition of the AJAX link:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red43\green145\blue175;}??\fs20 \cb2\highlight2 &amp;lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Control\cf0  \cf6 Language\cf3 ="C#"\cf0  \cf6 Inherits\cf3 ="System.Web.Mvc.ViewUserControl"\cf0  \cb2\highlight2 %&amp;gt;\par ??&amp;lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Import\cf0  \cf6 Namespace\cf3 ="System.Web.Mvc.Ajax"\cf0  \cb2\highlight2 %&amp;gt;\par ??&amp;lt;%\cf3\cb0\highlight0 =\cf0  \cf3 this\cf0 .Ajax.ActionLink((\cf3 string\cf0 )\cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ],\par ??    \cf5 "GetNext"\cf0 ,\par ??    \cf3 new\cf0  \{ number = \cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ] \}, \par ??    \cf3 new\cf0  \cf7 AjaxOptions\cf0  \{ UpdateTargetId = \cf5 "thespan"\cf0  \})\cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;@&lt;/span&gt; &lt;span style="color: #a31515"&gt;Control&lt;/span&gt; &lt;span style="color: red"&gt;Language&lt;/span&gt;&lt;span style="color: blue"&gt;="C#"&lt;/span&gt; &lt;span style="color: red"&gt;Inherits&lt;/span&gt;&lt;span style="color: blue"&gt;="System.Web.Mvc.ViewUserControl"&lt;/span&gt; &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;@&lt;/span&gt; &lt;span style="color: #a31515"&gt;Import&lt;/span&gt; &lt;span style="color: red"&gt;Namespace&lt;/span&gt;&lt;span style="color: blue"&gt;="System.Web.Mvc.Ajax"&lt;/span&gt; &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Ajax.ActionLink((&lt;span style="color: blue"&gt;string&lt;/span&gt;)&lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;],&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"GetNext"&lt;/span&gt;,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; {
number = &lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;]
}, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;AjaxOptions&lt;/span&gt; {
UpdateTargetId = &lt;span style="color: #a31515"&gt;"thespan"&lt;/span&gt; })&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The first parameter to the ActionLink method is simply the current number to render
as the link text. Since I'm using the untyped ViewData dictionary for this example,
I need to cast it to a string.
&lt;/p&gt;
&lt;p&gt;
The next parameter ("GetNext") indicates the Controller Action to invoke when the
link is clicked – I will cover that shortly.
&lt;/p&gt;
&lt;p&gt;
The third parameter is a Route Value that specifies that the parameter &lt;em&gt;number&lt;/em&gt; with
the correct value will be supplied to the GetNext Controller Action. It uses the number
stored in ViewData.
&lt;/p&gt;
&lt;p&gt;
The last parameter indicates the &lt;em&gt;id&lt;/em&gt; of the element to update. Recall from
before that this name was "thespan".
&lt;/p&gt;
&lt;p&gt;
The only missing piece now is the GetNext Controller Action:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 PartialViewResult\cf0  GetNext(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = (number + 1).ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .PartialView(\cf5 "NumberAjaxUserControl"\cf0 );\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PartialViewResult&lt;/span&gt; GetNext(&lt;span style="color: blue"&gt;int&lt;/span&gt; number)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;]
= (number + 1).ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.PartialView(&lt;span style="color: #a31515"&gt;"NumberAjaxUserControl"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this example I simply chose to increment the number by one, but I'm sure you can
imagine that this method could just as well perform a database lookup or something
similar.
&lt;/p&gt;
&lt;p&gt;
Notice that the method returns a PartialViewResult that uses the same user control
that I used to bootstrap the &lt;em&gt;thespan&lt;/em&gt; element. This means that every time
the link is clicked, the GetNext method is updated, and the exact same user control
is used to render the content that dynamically replaces the original content of the
element.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=73a82937-3edf-4e01-ae35-273a93d68160" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</comments>
      <category>ASP.NET MVC</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2691f07e-2813-4c4e-a861-43d7d04be692</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2691f07e-2813-4c4e-a861-43d7d04be692</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The expressiveness of WPF is amazing. I particularly like the databinding and templating
features. The ability to selectively render an object based on its type is very strong.
</p>
        <p>
When I recently began working with ASP.NET MVC (which I like so far), I quickly ran
into a scenario where I would have liked to have WPF's DataTemplates at my disposal.
Maybe it's just because I've become used to WPF, but I missed the feature and set
out to find out if something similar is possible in ASP.NET MVC.
</p>
        <p>
Before we dive into that, I'd like to present the 'problem' in WPF terms, but the
underlying View Model that I want to expose will be shared between both solutions.
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PresentationModel" border="0" alt="PresentationModel" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/PresentationModel_3.png" width="619" height="629" />
        </p>
        <p>
The main point is that the <em>Items</em> property exposes a polymorphic list. While
all items in this list share a common property (Name), they are otherwise different;
one contains a piece of Text, one contains a Color, and one is a complex item that
contains child items.
</p>
        <p>
When I render this list, I want each item to render according to its type.
</p>
        <p>
In WPF, this is fairly easy to accomplish with DataTemplates:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &lt;\cf3 ListBox.Resources\cf1 &gt;\par ??\cf3     \cf1 &lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedTextItem\cf1 \}"&gt;\par ??\cf3         \cf1 &lt;\cf3 StackPanel\cf1 &gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&gt;\par ??\cf3         \cf1 &lt;/\cf3 StackPanel\cf1 &gt;\par ??\cf3     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??\cf3     \cf1 &lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedColorItem\cf1 \}"&gt;\par ??\cf3         \cf1 &lt;\cf3 StackPanel\cf1 &gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&gt;\par ??\cf3             \cf1 &lt;\cf3 Ellipse\cf4  Height\cf1 ="25"\cf4  Width\cf1 ="25"\par ??\cf0                     \cf4  HorizontalAlignment\cf1 ="Left"\par ??\cf0                     \cf4  Fill\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Brush\}"\par ??\cf0                     \cf4  Stroke\cf1 ="DarkGray" /&gt;\par ??\cf3         \cf1 &lt;/\cf3 StackPanel\cf1 &gt;\par ??\cf3     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??\cf3     \cf1 &lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedComplexItem\cf1 \}"&gt;\par ??\cf3         \cf1 &lt;\cf3 StackPanel\cf1 &gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&gt;\par ??\cf3             \cf1 &lt;\cf3 ListBox\cf4  ItemsSource\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Children\}"\par ??\cf0                     \cf4  BorderThickness\cf1 ="0"&gt;\par ??\cf3                 \cf1 &lt;\cf3 ListBox.Resources\cf1 &gt;\par ??\cf3                     \cf1 &lt;\cf3 DataTemplate\par ??\cf0                        \cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 ChildItem\cf1 \}"&gt;\par ??\cf3                         \cf1 &lt;\cf3 TextBlock\par ??\cf0                            \cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&gt;\par ??\cf3                     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??\cf3                 \cf1 &lt;/\cf3 ListBox.Resources\cf1 &gt;\par ??\cf3             \cf1 &lt;/\cf3 ListBox\cf1 &gt;\par ??\cf3         \cf1 &lt;/\cf3 StackPanel\cf1 &gt;\par ??\cf3     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??&lt;/\cf3 ListBox.Resources\cf1 &gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: red"> DataType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type</span>
            <span style="color: red"> pm</span>
            <span style="color: blue">:</span>
            <span style="color: red">NamedTextItem</span>
            <span style="color: blue">}"&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Name}"</span>
          </pre>
          <pre style="margin: 0px">                      <span style="color: red"> FontWeight</span><span style="color: blue">="bold"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Text}"
/&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: red"> DataType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type</span>
            <span style="color: red"> pm</span>
            <span style="color: blue">:</span>
            <span style="color: red">NamedColorItem</span>
            <span style="color: blue">}"&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Name}"</span>
          </pre>
          <pre style="margin: 0px">                      <span style="color: red"> FontWeight</span><span style="color: blue">="bold"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">Ellipse</span>
            <span style="color: red"> Height</span>
            <span style="color: blue">="25"</span>
            <span style="color: red"> Width</span>
            <span style="color: blue">="25"</span>
          </pre>
          <pre style="margin: 0px">                    <span style="color: red"> HorizontalAlignment</span><span style="color: blue">="Left"</span></pre>
          <pre style="margin: 0px">                    <span style="color: red"> Fill</span><span style="color: blue">="{</span><span style="color: #a31515">Binding</span><span style="color: red"> Path</span><span style="color: blue">=Brush}"</span></pre>
          <pre style="margin: 0px">                    <span style="color: red"> Stroke</span><span style="color: blue">="DarkGray"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: red"> DataType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type</span>
            <span style="color: red"> pm</span>
            <span style="color: blue">:</span>
            <span style="color: red">NamedComplexItem</span>
            <span style="color: blue">}"&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Name}"</span>
          </pre>
          <pre style="margin: 0px">                      <span style="color: red"> FontWeight</span><span style="color: blue">="bold"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">ListBox</span>
            <span style="color: red"> ItemsSource</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Children}"</span>
          </pre>
          <pre style="margin: 0px">                    <span style="color: red"> BorderThickness</span><span style="color: blue">="0"&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
          </pre>
          <pre style="margin: 0px">                       <span style="color: red"> DataType</span><span style="color: blue">="{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type</span><span style="color: red"> pm</span><span style="color: blue">:</span><span style="color: red">ChildItem</span><span style="color: blue">}"&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
          </pre>
          <pre style="margin: 0px">                           <span style="color: red"> Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding</span><span style="color: red"> Path</span><span style="color: blue">=Text}"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">ListBox</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
        </div>
        <p>
Each DataTemplate is contained within a ListBox. When the ListBox binds to each item
in the <em>Items</em> list, it automatically picks the correct template for the item.
</p>
        <p>
The result is something like this:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="WpfApp" border="0" alt="WpfApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/WpfApp_5.png" width="167" height="333" />
        </p>
        <p>
The NamedTextItem is rendered as a box containing the Name and the Text on two separate
lines; the NamedColorItem is rendered as a box containing the Name and a circle filled
with the Color defined by the item; and the NamedComplexItem is rendered as a box
with the Name and each child of the Children list.
</p>
        <p>
This is all implemented declaratively without a single line of imperative UI code.
</p>
        <p>
Is it possible to do the same in ASP.NET MVC?
</p>
        <p>
To my knowledge (but please correct me if I'm wrong), ASP.NET MVC has no explicit
concept of a DataTemplate, so we will have to mimic it. The following describes the
best I've been able to come up with so far.
</p>
        <p>
In ASP.NET MVC, there's no declarative databinding, so we will need to loop through
the list of items. My View page derives from ViewPage&lt;MyViewModel&gt;, so I can
write
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&gt;\par ??\cf0    \cb2\highlight2 &lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;/\cf5 div\cf4 &gt;\par ??\cf0\cb2\highlight2 &lt;%\cb0\highlight0  \} \cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">foreach</span> (<span style="color: blue">var</span> item <span style="color: blue">in</span><span style="color: blue">this</span>.Model.Items)</pre>
          <pre style="margin: 0px">   { <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;</span><span style="color: #a31515">div</span><span style="color: red">class</span><span style="color: blue">="ploeh"&gt;</span></pre>
          <pre style="margin: 0px">   <span style="background: #ffee62">&lt;%</span><span style="color: green">//
Render each item </span><span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span> } <span style="background: #ffee62">%&gt;</span></pre>
        </div>
        <p>
The challenge is to figure out how to render each item according to its own template.
</p>
        <p>
To define the templates, I create a UserControl for each item. The NamedTextItemUserControl
derives from ViewUserControl&lt;NamedTextItem&gt;, which gives me a strongly typed
Model:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &lt;\cf3 div\cf1 &gt;&lt;\cf3 strong\cf1 &gt;\cf0\cb5\highlight5 &lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Name \cb5\highlight5 %&gt;\cf1\cb0\highlight0 &lt;/\cf3 strong\cf1 &gt;&lt;/\cf3 div\cf1 &gt;\par ??&lt;\cf3 div\cf1 &gt;\cf0\cb5\highlight5 &lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Text \cb5\highlight5 %&gt;\cf1\cb0\highlight0 &lt;/\cf3 div\cf1 &gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">div</span>
            <span style="color: blue">&gt;&lt;</span>
            <span style="color: #a31515">strong</span>
            <span style="color: blue">&gt;</span>
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">=</span>
            <span style="color: blue">this</span>.Model.Name <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">div</span>
            <span style="color: blue">&gt;</span>
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">=</span>
            <span style="color: blue">this</span>.Model.Text <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
        </div>
        <p>
The other two UserControls are implemented similarly.
</p>
        <p>
A UserControl can be rendered using the RenderPartial extension method, so the only
thing left is to select the correct UserControl name for each item. It would be nice
to be able to do this in markup, like WPF, but I'm not aware of any way that is possible.
</p>
        <p>
I will have to resort to code, but we can at least strive for code that is as declarative
in style as possible.
</p>
        <p>
First, I need to define the map from type to UserControl:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cb2\highlight2 &lt;%\par ??\cb0\highlight0     \cf4 var\cf0  dataTemplates = \cf4 new\cf0  \cf5 Dictionary\cf0 &lt;\cf5 Type\cf0 , \cf4 string\cf0 &gt;();\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedTextItem\cf0 )] =\par ??        \cf6 "NamedTextItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedColorItem\cf0 )] =\par ??        \cf6 "NamedColorItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedComplexItem\cf0 )] =\par ??        \cf6 "NamedComplexItemUserControl"\cf0 ;\par ??\cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
          </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> dataTemplates
= <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: blue">string</span>&gt;();</pre>
          <pre style="margin: 0px">    dataTemplates[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NamedTextItem</span>)]
=</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"NamedTextItemUserControl"</span>;</pre>
          <pre style="margin: 0px">    dataTemplates[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NamedColorItem</span>)]
=</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"NamedColorItemUserControl"</span>;</pre>
          <pre style="margin: 0px">    dataTemplates[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NamedComplexItem</span>)]
=</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"NamedComplexItemUserControl"</span>;</pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">%&gt;</span>
          </pre>
        </div>
        <p>
Next, I can use this map to render each item correctly:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&gt;\par ??\cf0    \cb2\highlight2 &lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cb2\highlight2 &lt;%\cb0\highlight0  \cf4 this\cf0 .Html.RenderPartial(dataTemplates[item.GetType()],\par ??                             item); \cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;/\cf5 div\cf4 &gt;\par ??\cf0\cb2\highlight2 &lt;%\cb0\highlight0  \} \cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">foreach</span> (<span style="color: blue">var</span> item <span style="color: blue">in</span><span style="color: blue">this</span>.Model.Items)</pre>
          <pre style="margin: 0px">   { <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;</span><span style="color: #a31515">div</span><span style="color: red">class</span><span style="color: blue">="ploeh"&gt;</span></pre>
          <pre style="margin: 0px">   <span style="background: #ffee62">&lt;%</span><span style="color: green">//
Render each item </span><span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="background: #ffee62">&lt;%</span><span style="color: blue">this</span>.Html.RenderPartial(dataTemplates[item.GetType()],</pre>
          <pre style="margin: 0px">                            item); <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span> } <span style="background: #ffee62">%&gt;</span></pre>
        </div>
        <p>
This is definitely less pretty than with WPF, but if you overlook the aesthetics and
focus on the structure of the code, it's darn close to markup. The Cyclomatic Complexity
of the page is only <em>2</em>, and that's even because of the <em>foreach</em> statement
that we need in any case.
</p>
        <p>
The resulting page looks like this:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="AspNetMvcApp" border="0" alt="AspNetMvcApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/AspNetMvcApp_1.png" width="156" height="246" />
        </p>
        <p>
My HTML skills aren't good enough to draw circles with markup, so I had to replace
them with blocks, but apart from that, the result is pretty much the same.
</p>
        <p>
A potential improvement on this technique could be to embed the knowledge of the UserControl
into each item. ASP.NET MVC Controllers already know of Views in an abstract sense,
so letting the View Model know about a UserControl (identified as a string) may be
conceptually sound.
</p>
        <p>
The advantage would be that we could get rid of the Dictionary in the ViewPage and
instead let the item itself tell us the name of the UserControl that should be used
to render it.
</p>
        <p>
The disadvantage would be that we lose some flexibility. It would then require a recompilation
of the application if we wanted to render an item using a different UserControl.
</p>
        <p>
The technique outlined here represents an explorative work in progress, so comments
are welcome.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2691f07e-2813-4c4e-a861-43d7d04be692" />
      </body>
      <title>DataTemplating In ASP.NET MVC</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</guid>
      <link>http://blog.ploeh.dk/2009/07/16/DataTemplatingInASPNETMVC.aspx</link>
      <pubDate>Thu, 16 Jul 2009 19:33:48 GMT</pubDate>
      <description>&lt;p&gt;
The expressiveness of WPF is amazing. I particularly like the databinding and templating
features. The ability to selectively render an object based on its type is very strong.
&lt;/p&gt;
&lt;p&gt;
When I recently began working with ASP.NET MVC (which I like so far), I quickly ran
into a scenario where I would have liked to have WPF's DataTemplates at my disposal.
Maybe it's just because I've become used to WPF, but I missed the feature and set
out to find out if something similar is possible in ASP.NET MVC.
&lt;/p&gt;
&lt;p&gt;
Before we dive into that, I'd like to present the 'problem' in WPF terms, but the
underlying View Model that I want to expose will be shared between both solutions.
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PresentationModel" border="0" alt="PresentationModel" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/PresentationModel_3.png" width="619" height="629"&gt; 
&lt;/p&gt;
&lt;p&gt;
The main point is that the &lt;em&gt;Items&lt;/em&gt; property exposes a polymorphic list. While
all items in this list share a common property (Name), they are otherwise different;
one contains a piece of Text, one contains a Color, and one is a complex item that
contains child items.
&lt;/p&gt;
&lt;p&gt;
When I render this list, I want each item to render according to its type.
&lt;/p&gt;
&lt;p&gt;
In WPF, this is fairly easy to accomplish with DataTemplates:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &amp;lt;\cf3 ListBox.Resources\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedTextItem\cf1 \}"&amp;gt;\par ??\cf3         \cf1 &amp;lt;\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&amp;gt;\par ??\cf3         \cf1 &amp;lt;/\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedColorItem\cf1 \}"&amp;gt;\par ??\cf3         \cf1 &amp;lt;\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 Ellipse\cf4  Height\cf1 ="25"\cf4  Width\cf1 ="25"\par ??\cf0                     \cf4  HorizontalAlignment\cf1 ="Left"\par ??\cf0                     \cf4  Fill\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Brush\}"\par ??\cf0                     \cf4  Stroke\cf1 ="DarkGray" /&amp;gt;\par ??\cf3         \cf1 &amp;lt;/\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedComplexItem\cf1 \}"&amp;gt;\par ??\cf3         \cf1 &amp;lt;\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 ListBox\cf4  ItemsSource\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Children\}"\par ??\cf0                     \cf4  BorderThickness\cf1 ="0"&amp;gt;\par ??\cf3                 \cf1 &amp;lt;\cf3 ListBox.Resources\cf1 &amp;gt;\par ??\cf3                     \cf1 &amp;lt;\cf3 DataTemplate\par ??\cf0                        \cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 ChildItem\cf1 \}"&amp;gt;\par ??\cf3                         \cf1 &amp;lt;\cf3 TextBlock\par ??\cf0                            \cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&amp;gt;\par ??\cf3                     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??\cf3                 \cf1 &amp;lt;/\cf3 ListBox.Resources\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;/\cf3 ListBox\cf1 &amp;gt;\par ??\cf3         \cf1 &amp;lt;/\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??&amp;lt;/\cf3 ListBox.Resources\cf1 &amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;NamedTextItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Name}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;="bold"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Text}"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;NamedColorItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Name}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;="bold"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Ellipse&lt;/span&gt;&lt;span style="color: red"&gt; Height&lt;/span&gt;&lt;span style="color: blue"&gt;="25"&lt;/span&gt;&lt;span style="color: red"&gt; Width&lt;/span&gt;&lt;span style="color: blue"&gt;="25"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;="Left"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; Fill&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Brush}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; Stroke&lt;/span&gt;&lt;span style="color: blue"&gt;="DarkGray"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;NamedComplexItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Name}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;="bold"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox&lt;/span&gt;&lt;span style="color: red"&gt; ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Children}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; BorderThickness&lt;/span&gt;&lt;span style="color: blue"&gt;="0"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ChildItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Text}"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Each DataTemplate is contained within a ListBox. When the ListBox binds to each item
in the &lt;em&gt;Items&lt;/em&gt; list, it automatically picks the correct template for the item.
&lt;/p&gt;
&lt;p&gt;
The result is something like this:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="WpfApp" border="0" alt="WpfApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/WpfApp_5.png" width="167" height="333"&gt; 
&lt;/p&gt;
&lt;p&gt;
The NamedTextItem is rendered as a box containing the Name and the Text on two separate
lines; the NamedColorItem is rendered as a box containing the Name and a circle filled
with the Color defined by the item; and the NamedComplexItem is rendered as a box
with the Name and each child of the Children list.
&lt;/p&gt;
&lt;p&gt;
This is all implemented declaratively without a single line of imperative UI code.
&lt;/p&gt;
&lt;p&gt;
Is it possible to do the same in ASP.NET MVC?
&lt;/p&gt;
&lt;p&gt;
To my knowledge (but please correct me if I'm wrong), ASP.NET MVC has no explicit
concept of a DataTemplate, so we will have to mimic it. The following describes the
best I've been able to come up with so far.
&lt;/p&gt;
&lt;p&gt;
In ASP.NET MVC, there's no declarative databinding, so we will need to loop through
the list of items. My View page derives from ViewPage&amp;lt;MyViewModel&amp;gt;, so I can
write
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&amp;gt;\par ??\cf0    \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;/\cf5 div\cf4 &amp;gt;\par ??\cf0\cb2\highlight2 &amp;lt;%\cb0\highlight0  \} \cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue"&gt;var&lt;/span&gt; item &lt;span style="color: blue"&gt;in&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Items)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; { &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt; &lt;span style="color: red"&gt;class&lt;/span&gt;&lt;span style="color: blue"&gt;="ploeh"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: green"&gt;//
Render each item &lt;/span&gt;&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; } &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The challenge is to figure out how to render each item according to its own template.
&lt;/p&gt;
&lt;p&gt;
To define the templates, I create a UserControl for each item. The NamedTextItemUserControl
derives from ViewUserControl&amp;lt;NamedTextItem&amp;gt;, which gives me a strongly typed
Model:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &amp;lt;\cf3 div\cf1 &amp;gt;&amp;lt;\cf3 strong\cf1 &amp;gt;\cf0\cb5\highlight5 &amp;lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Name \cb5\highlight5 %&amp;gt;\cf1\cb0\highlight0 &amp;lt;/\cf3 strong\cf1 &amp;gt;&amp;lt;/\cf3 div\cf1 &amp;gt;\par ??&amp;lt;\cf3 div\cf1 &amp;gt;\cf0\cb5\highlight5 &amp;lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Text \cb5\highlight5 %&amp;gt;\cf1\cb0\highlight0 &amp;lt;/\cf3 div\cf1 &amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;strong&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Name &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;strong&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Text &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The other two UserControls are implemented similarly.
&lt;/p&gt;
&lt;p&gt;
A UserControl can be rendered using the RenderPartial extension method, so the only
thing left is to select the correct UserControl name for each item. It would be nice
to be able to do this in markup, like WPF, but I'm not aware of any way that is possible.
&lt;/p&gt;
&lt;p&gt;
I will have to resort to code, but we can at least strive for code that is as declarative
in style as possible.
&lt;/p&gt;
&lt;p&gt;
First, I need to define the map from type to UserControl:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cb2\highlight2 &amp;lt;%\par ??\cb0\highlight0     \cf4 var\cf0  dataTemplates = \cf4 new\cf0  \cf5 Dictionary\cf0 &amp;lt;\cf5 Type\cf0 , \cf4 string\cf0 &amp;gt;();\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedTextItem\cf0 )] =\par ??        \cf6 "NamedTextItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedColorItem\cf0 )] =\par ??        \cf6 "NamedColorItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedComplexItem\cf0 )] =\par ??        \cf6 "NamedComplexItemUserControl"\cf0 ;\par ??\cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; dataTemplates
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataTemplates[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;NamedTextItem&lt;/span&gt;)]
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"NamedTextItemUserControl"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataTemplates[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;NamedColorItem&lt;/span&gt;)]
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"NamedColorItemUserControl"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataTemplates[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;NamedComplexItem&lt;/span&gt;)]
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"NamedComplexItemUserControl"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Next, I can use this map to render each item correctly:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&amp;gt;\par ??\cf0    \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf4 this\cf0 .Html.RenderPartial(dataTemplates[item.GetType()],\par ??                             item); \cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;/\cf5 div\cf4 &amp;gt;\par ??\cf0\cb2\highlight2 &amp;lt;%\cb0\highlight0  \} \cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue"&gt;var&lt;/span&gt; item &lt;span style="color: blue"&gt;in&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Items)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; { &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt; &lt;span style="color: red"&gt;class&lt;/span&gt;&lt;span style="color: blue"&gt;="ploeh"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: green"&gt;//
Render each item &lt;/span&gt;&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Html.RenderPartial(dataTemplates[item.GetType()],&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; item); &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; } &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is definitely less pretty than with WPF, but if you overlook the aesthetics and
focus on the structure of the code, it's darn close to markup. The Cyclomatic Complexity
of the page is only &lt;em&gt;2&lt;/em&gt;, and that's even because of the &lt;em&gt;foreach&lt;/em&gt; statement
that we need in any case.
&lt;/p&gt;
&lt;p&gt;
The resulting page looks like this:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="AspNetMvcApp" border="0" alt="AspNetMvcApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/AspNetMvcApp_1.png" width="156" height="246"&gt; 
&lt;/p&gt;
&lt;p&gt;
My HTML skills aren't good enough to draw circles with markup, so I had to replace
them with blocks, but apart from that, the result is pretty much the same.
&lt;/p&gt;
&lt;p&gt;
A potential improvement on this technique could be to embed the knowledge of the UserControl
into each item. ASP.NET MVC Controllers already know of Views in an abstract sense,
so letting the View Model know about a UserControl (identified as a string) may be
conceptually sound.
&lt;/p&gt;
&lt;p&gt;
The advantage would be that we could get rid of the Dictionary in the ViewPage and
instead let the item itself tell us the name of the UserControl that should be used
to render it.
&lt;/p&gt;
&lt;p&gt;
The disadvantage would be that we lose some flexibility. It would then require a recompilation
of the application if we wanted to render an item using a different UserControl.
&lt;/p&gt;
&lt;p&gt;
The technique outlined here represents an explorative work in progress, so comments
are welcome.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2691f07e-2813-4c4e-a861-43d7d04be692" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>WPF</category>
    </item>
  </channel>
</rss>