Created
August 13, 2013 13:10
-
-
Save odenijs/6220916 to your computer and use it in GitHub Desktop.
Render a partial view as a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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