Skip to content

Instantly share code, notes, and snippets.

@StrutTower
Created May 27, 2019 01:09
Show Gist options
  • Save StrutTower/d5aa7677f5bb22fb5a5c28c0faab885c to your computer and use it in GitHub Desktop.
Save StrutTower/d5aa7677f5bb22fb5a5c28c0faab885c to your computer and use it in GitHub Desktop.
MVC 5 Render View to String
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace Website.Infrastructure {
public static class ViewExtensions {
//Renders the view to a string
public static string RenderToString(this PartialViewResult partialView) {
HttpContext httpContext = HttpContext.Current;
if (httpContext == null) {
throw new NotSupportedException("An HTTP context is required to render the partial view to a string");
}
string controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
ControllerBase controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory()
.CreateController(httpContext.Request.RequestContext, controllerName);
ControllerContext controllerContext = new ControllerContext(httpContext.Request.RequestContext, controller);
string viewName = partialView.ViewName;
if (string.IsNullOrWhiteSpace(viewName)) {
// Use the action name if a view name is not supplied
viewName = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();
}
var view = ViewEngines.Engines.FindPartialView(controllerContext, viewName).View;
using (StringWriter sw = new StringWriter())
using (HtmlTextWriter tw = new HtmlTextWriter(sw)) {
view.Render(new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw), tw);
return sw.GetStringBuilder().ToString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment