I have been experimenting with rendering an view to a string using methods outlines here:
The issue is that I need to call my controller action which does not happen when calling View.Render.
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
viewResult.View.Render(viewContext, sw);
My question is, how can I call RenderAction on an arbitrary controller passing in a route? I am trying to composite together the results of a number of partial views into a single result which will get passed back to the browser.
My code so far. Works except that the action method is not called.
public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
var route = new RouteData();
route.Values.Add("controller", "Test1");
route.Values.Add("action", "Index");
var controller1 = new Test1Controller();
var controllerContext = new ControllerContext(new RequestContext(this.ControllerContext.HttpContext, route), controller1);
controller1.ControllerContext = controllerContext;
var viewString = controller1.RenderPartialViewToString("~/Views/Test1/Index.cshtml", (object)model);
My goal is to create a simple CMS system that composites together the results of a number of controller actions/views and outputs them into a layout.
I have a primary controller action that retrieves a page description from the database. The code loops over a list of other controllers and calls their actions which results in a dynamic object model and a list of partial html snippets that is handed off to a custom WebViewPage.