Created
April 18, 2013 04:45
-
-
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
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
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