title: Delayed rendering of content until end of layout page
body: <p>In our application we have user controls which render HTML and generate JS which should be combined and output at the bottom of our page. The way I am accomplishing the JS part is by adding to the ViewData in the helper method to generate the control. The bottom of the layout page then renders the full block of JS at the end of the body.</p>
  
  <p>View:</p>
  
  <pre><code>@UserControlHelpers.RenderDataGrid(grid)
  </code></pre>
  
  <p>Helper class:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Renders a DataGrid user control using partial views rendered to strings
  /// &lt;/summary&gt;
  /// &lt;param name="grid"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public IHtmlString RenderDataGrid(Models.UserControls.DataGrid grid)
  {
      // Generate the JS for the control, storing it for later
      this.HtmlHelper.ViewData["dataGridJS"] += this.HtmlHelper.Partial("~/Views/UserControls/DataGridJS.cshtml", grid).ToString();
  
      // Immediately render the HTML for the grid
      return this.HtmlHelper.Raw(this.HtmlHelper.Partial("~/Views/UserControls/DataGridHTML.cshtml", grid).ToString());
  }
  </code></pre>
  
  <p>Layout:</p>
  
  <pre><code>&lt;html&gt;
  &lt;body&gt;
  @Html.Raw(UserControlHelpers.HtmlHelper.ViewData["dataGridJS"])
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The problem is when we render partial view which contains a grid. The grid JS does not get into the ViewData object I am outputting, but a separate instance of the ViewData. When we just put the grid on the main view, it works fine.</p>
  
  <p>Is there a better way to do this?</p>