Views


Serverside rendering Views

With a fake controller you can actually let Razoer view engien create the HTML server-side from anywhere inside your code. All you need to do is add a FakeController and then call it with the path of the View and your model to be used with it.

 

public class FakeController : Controller
{
    // GET: Fake
    protected override void ExecuteCore() { }

    public static string RenderViewToString(string controllerName, string viewName, object viewData)
    {
        using (var writer = new StringWriter())
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", controllerName);
            var fakeControllerContext =
              new ControllerContext(
                new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://localhost", null),
                  new HttpResponse(null))), routeData, new FakeController());
            var razorViewEngine = new RazorViewEngine();
            var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

            var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View,
              new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
            razorViewResult.View.Render(viewContext, writer);
            return writer.ToString();

        }
    }
}

 

code = FakeController.RenderViewToString(
                        "Fake", 
                        "~/Views/myView.cshtml", 
                        new MyViewModel()
                        {
                            Title = "PageTitle"
                        });

Published: 2016-08-25