I often see questions on the net about how to render a view to a string so it can be used somewhere.
My approach allows doing it without thinking about all the boilerplate code. Additionally not only the ViewResult can be rendered into a string but just about any type of the result. Here is example on how to return a JSON including the result of the view as additional information:
// Controller Action:
public JsonResult DoSomething() {
var viewString = View("TheViewToRender").Capture(ControllerContext);
return new JsonResult {JsonRequestBehavior = JsonRequestBehavior.AllowGet,Data = new {
time = DateTime.Now,html = viewString}};}
This can be done with 2 simple utility classes below. Just include them somewhere into your project.
public class ResponseCapture : IDisposable {private readonly HttpResponseBase response;private readonly TextWriter originalWriter;private StringWriter localWriter;
public ResponseCapture(HttpResponseBase response) {
this.response = response;
originalWriter = response.Output;localWriter = new StringWriter();
response.Output = localWriter;}public override string ToString() {localWriter.Flush();return localWriter.ToString();
}public void Dispose() {if (localWriter != null) {localWriter.Dispose();localWriter = null;
response.Output = originalWriter;}}}public static class ActionResultExtensions {public static string Capture(this ActionResult result, ControllerContext controllerContext) {using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response)) {result.ExecuteResult(controllerContext);return it.ToString();
}}}
Enjoy and let me know if it works for you.