How to Rendering ASP.NET MVC 1.0, 2.0 RC, 3 and 4 Razor Views to String

ReliableASPNETHosting.com | The ASP.NET MVC Razor implementation is closely tied to ASP.NET and MVC and the View template (WebViewPage class) includes a few MVC-specific features as well as back references to the controller. In other words MVC Razor is designed with MVC in mind. With Razor, you can create a custom Razor Engine that can be used in any .NET environment. Razor is the best view engine available for MVC as its much cleaner and easy to write and read. This view engine is compatible with unit testing frameworks.

mvc_05

In this article, I will demonstrate how you can render ASP.NET MVC Razor Views in ASP.Net MVC 1.0, 2.0 RC, 3 and 4 .
Basically, all you do is create a fake HttpContext for the view to render itself.  This is an extensions method of the HtmlHelper that processes a partial view through the default MVC view engine and then renders it to the response stream.

Best OFFER Unlimited ASP.NET MVC 6 Hosting in Europe Click here !!

This works on ASP.NET MVC 1.0  changing Headers on the original HttpResponse doesn’t throw the “Server cannot set content type after HTTP headers have been sent ” exception.

/// <summary>Renders a view to string.</summary>
public static string RenderViewToString(this Controller controller, string viewName, object viewData) {

Create memory writer.

var sb = new StringBuilder();
var memWriter = new StringWriter(sb);

 Create fake http context to render the view.

var fakeResponse = new HttpResponse(memWriter);
    var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
    var fakeControllerContext = new ControllerContext(
        new HttpContextWrapper(fakeContext),
        controller.ControllerContext.RouteData,
        controller.ControllerContext.Controller);
    var oldContext = HttpContext.Current;
    HttpContext.Current = fakeContext;
  Use HtmlHelper to render partial view to fake context.
    var html = new HtmlHelper(new ViewContext(fakeControllerContext,
        new FakeView(), new ViewDataDictionary(), new TempDataDictionary()),
        new ViewPage());
    html.RenderPartial(viewName, viewData);
Restore context.
    HttpContext.Current = oldContext;  
    //Flush memory and return output
    memWriter.Flush();
    return sb.ToString();}
Fake IView implementation used to instantiate an HtmlHelper.
public class FakeView : IView {
    #region IView Members
    public void Render(ViewContext viewContext, System.IO.TextWriter writer) {
        throw new NotImplementedException();
    }    #endregion
}

 

In ASP.NET MVC 2.0 RC, the code changes a bit because we have to pass in the StringWriter used to write the view into the ViewContext:
Use HtmlHelper to render partial view to fake context.

//...
var html = new HtmlHelper(
    new ViewContext(fakeControllerContext, new FakeView(),
        new ViewDataDictionary(), new TempDataDictionary(), memWriter),
    new ViewPage());
html.RenderPartial(viewName, viewData);
//...

 In MVC 3 you can used this code :

public static string RazorRender(Controller context, string DefaultAction)
{
string Cache = string.Empty;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.TextWriter tw = new System.IO.StringWriter(sb);
RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);
Cache = sb.ToString();
return Cache;
}
public static string RenderRazorViewToString(string viewName, object model)
        {
ViewData.Model = model;
using (var sw = new StringWriter())
            {
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public static class HtmlHelperExtensions
        {
public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
            {
ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);
if (result.View != null)
                {
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
                    {
using (HtmlTextWriter output = new HtmlTextWriter(sw))
                        {
ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
result.View.Render(viewContext, output);
}
}
return sb.ToString();

}
return String.Empty;
            }
        }

 This code worked in MVC 4 :

public string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    using (var sw = new StringWriter()) {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

 I hope you will enjoy this Article, and I hope you will refer this article for your need.

 

Save

About the author: Alexia Pamelov