Is there a way to call a Controller's ParitalViewResult
from code and return the entire view as a String. I am looking to call this Controller and Action from information I have in the database, no hard-coded controller calls, as dynamic as possible.
For example, I have a TestscController
with the following PartialViewResult
(code is incomplete, just a placeholder):
public PartialViewResult _Display ()
{
return PartialView();
}
I have a ViewExtension that will render a View to String, but it never hits the TestsController
's _Display. It just runs the .cshtml
.
I can call the following:
strView = PartialView("~/Views/Tests/_Display.cshtml", model).RenderToString();
With this ViewExtension (which works well, but doesn't hit the controller:
public static string RenderToString(this PartialViewResult partialView)
{
var httpContext = HttpContext.Current;
if (httpContext == null)
{
throw new NotSupportedException("An HTTP context is required to render the partial view to a string");
}
var controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
var controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory().CreateController(httpContext.Request.RequestContext, controllerName);
var controllerContext = new ControllerContext(httpContext.Request.RequestContext, controller);
var view = ViewEngines.Engines.FindPartialView(controllerContext, partialView.ViewName).View;
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
using (var tw = new HtmlTextWriter(sw))
{
view.Render(new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw), tw);
}
}
return sb.ToString();
}
Let me know if I can provide additional details.