Skip to content

Instantly share code, notes, and snippets.

@micklaw
Created October 16, 2015 07:34
Show Gist options
  • Save micklaw/25afcaebb0a1abade266 to your computer and use it in GitHub Desktop.
Save micklaw/25afcaebb0a1abade266 to your computer and use it in GitHub Desktop.
namespace Something
{
public class BaseController : Controller
{
#region partial rendering in controller
public string RenderPartialToString(string partialViewName, object model)
{
InvalidateControllerContext();
var view = ViewEngines.Engines.FindPartialView(ControllerContext, partialViewName).View;
string result = RenderViewToString(view, model);
return result;
}
public string RenderViewToString(string viewName, object model)
{
InvalidateControllerContext();
var view = ViewEngines.Engines.FindView(ControllerContext, viewName, null).View;
string result = RenderViewToString(view, model);
return result;
}
public string RenderViewToString(IView view, object model)
{
InvalidateControllerContext();
string result = null;
if (view != null)
{
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
var viewContext = new ViewContext(ControllerContext, view, new ViewDataDictionary(model), new TempDataDictionary(), writer);
view.Render(viewContext, writer);
writer.Flush();
}
result = sb.ToString();
}
return result;
}
private void InvalidateControllerContext()
{
if (ControllerContext == null)
{
var context = new ControllerContext(System.Web.HttpContext.Current.Request.RequestContext, this);
ControllerContext = context;
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment