Skip to content

Instantly share code, notes, and snippets.

@odenijs
Created August 13, 2013 13:10
Show Gist options
  • Save odenijs/6220916 to your computer and use it in GitHub Desktop.
Save odenijs/6220916 to your computer and use it in GitHub Desktop.
Render a partial view as a string
/// <summary>
/// Renders the partial view to string.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="partialViewName">Partial name of the view.</param>
/// <param name="viewData">The view data.</param>
/// <param name="tempData">The temp data.</param>
/// <returns></returns>
public static string RenderPartialViewToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
{
ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);
if (result.View != null)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter output = new HtmlTextWriter(sw))
{
ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
result.View.Render(viewContext, output);
}
}
return sb.ToString();
}
return String.Empty;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment