3

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.

Derek
  • 653
  • 7
  • 20
  • Not sure what you mean. You mean like this: `var c = new TestscController(); c._Display();`? – CodingYoshi May 09 '18 at 01:41
  • Why do you need to render the partial view as a string? – Andrew May 09 '18 at 04:23
  • Possible duplicate of [How to Render Partial View into a String](https://stackoverflow.com/questions/2537741/how-to-render-partial-view-into-a-string) – ADyson May 09 '18 at 08:27

0 Answers0