Skip to content

Instantly share code, notes, and snippets.

@robcthegeek
Created November 21, 2012 11:41
Show Gist options
  • Save robcthegeek/4124478 to your computer and use it in GitHub Desktop.
Save robcthegeek/4124478 to your computer and use it in GitHub Desktop.
Rendering Partial Views to Strings in ASP.NET MVC

Rendering a Partial to a String

Sometimes required when you just don't have your JavaScript templating in place..

I tend to wrap this in a protected method in a base controller:

protected string RenderToString(string partial, object model)
{
    return this.RenderPartialToString(partial, model);
}

You can then call it like so: var html = RenderToString("~/Path/To/Partial.cshtml", viewModel);

Props to Kevin Craft at CraftyCode for this.

using System.IO;
using System.Web.Mvc;
namespace Website.App.Extensions
{
public static class ControllerExtensions
{
public static string RenderPartialToString(this Controller controller, string partial, object model)
{
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partial);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment