title: Rendering corruption in ASP.NET MVC 3 Razor View Engine Using Custom HTML Extension
body: <p>I just installed ASP.NET MVC 3 RC to try and upgrade an MVC 2 site.  I encountered a rendering problem which I managed to repro outside of the site, using an MVC 3 project created from scratch.</p>
  
  <p>Here is my Razor cshtml view:</p>
  
  <pre><code>@using Mvc3RCTest.Helpers
  
  &lt;h2&gt;Demo Render Bug&lt;/h2&gt;
  
  &lt;div class="content"&gt;
  @{ Html.RenderTest(); }
  &lt;/div&gt;
  </code></pre>
  
  <p>RenderTest is an HTML extension defined as follows:</p>
  
  <pre><code>using System.Web;
  using System.Web.Mvc;
  
  namespace Mvc3RCTest.Helpers
  {
      public static class TestHtmlExtensions
      {
          public static void RenderTest(this HtmlHelper html)
          {
              HttpResponseBase r = html.ViewContext.HttpContext.Response;
              r.Write("&lt;ul&gt;");
              for (int i = 0; i &lt; 10; ++i)
              {
                  r.Write("&lt;li&gt;" + i + "&lt;/li&gt;");
              }
              r.Write("&lt;/ul&gt;");
          }
      }
  }
  </code></pre>
  
  <p>When this is rendered, the HTML looks like the following:</p>
  
  <pre><code>&lt;ul&gt;&lt;li&gt;0&lt;/li&gt;&lt;li&gt;1&lt;/li&gt;&lt;li&gt;2&lt;/li&gt;&lt;li&gt;3&lt;/li&gt;&lt;li&gt;4&lt;/li&gt;&lt;li&gt;5&lt;/li&gt;&lt;li&gt;6&lt;/li&gt;&lt;li&gt;7&lt;/li&gt;&lt;li&gt;8&lt;/li&gt;&lt;li&gt;9&lt;/li&gt;&lt;/ul&gt;
  &lt;h2&gt;Demo Render Bug&lt;/h2&gt;
  
  &lt;div class="content"&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>As you can see, the output of the RenderTest HTML extension was incorrectly emitted <em>before</em> the rest of the Razor template.  It seems as if the Razor rendering engine is trying to cache the entire output, without being aware that HTML extensions can write directly to the output.</p>
  
  <p>Has anyone else seen this problem?  Anyone know how to work around this, without having to redo all of my HTML extensions not to write directly to the output?</p>