Created
October 16, 2015 07:34
-
-
Save micklaw/25afcaebb0a1abade266 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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