Skip to content

Instantly share code, notes, and snippets.

@aaronpowell
Created April 18, 2013 04:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronpowell/5410187 to your computer and use it in GitHub Desktop.
Save aaronpowell/5410187 to your computer and use it in GitHub Desktop.
Execute a Razor view server side in a MVC project. I'm returning the HTML in a JSON blob for this example
public class PreExecutingResult : JsonResult {
private ViewResult viewResult;
private object model;
public PreExecutingResult(string viewName, object model) {
viewResult = new ViewResult {
ViewName = viewName
};
viewResult.ViewData.Model = model;
this.model = model;
}
public override void ExecuteResult(ControllerContext context)
{
var builder = new StringBuilder();
using (var stringWriter = new StringWriter(builder))
{
using (var htmlTextWriter = new HtmlTextWriter(stringWriter))
{
var controller = context.Controller;
var currentContext = controller.ControllerContext.HttpContext;
try
{
var currentRequest = HttpContext.Current.ApplicationInstance.Context.Request;
var currentUser = HttpContext.Current.ApplicationInstance.Context.User;
var newResponse = new HttpResponse(htmlTextWriter);
var newContext = new HttpContextWrapper(
new HttpContext(currentRequest, newResponse)
{
User = currentUser
});
controller.ControllerContext.HttpContext = newContext;
viewResult.ExecuteResult(controller.ControllerContext);
newResponse.Flush();
htmlTextWriter.Flush();
stringWriter.Flush();
}
finally
{
// and no matter what happens, set the context back!
controller.ControllerContext.HttpContext = currentContext;
}
}
}
Data = new
{
html = builder.ToString(),
model = model
};
base.ExecuteResult(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment