Get html from MVC 4 view into a string

asp.net-mvc-4, c#-4.0

Solution

You can create a base controller which obviously extends a controller and use above function in the base controller and other controller which extends this base controller will be able to use it. However the ControllerContext must be used as

Request.RequestContext

And Hence your BaseController will be like

public class BaseController: Controller
{
//your function here
}

And your ToHtml() function will be

protected virtual string ToHtml(string viewToRender, ViewDataDictionary viewData )
{
   var controllerContext=Request.RequestContext;
   var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

   StringWriter output;
   using (output = new StringWriter())
   {
      var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
      result.View.Render(viewContext, output);
      result.ViewEngine.ReleaseView(controllerContext, result.View);
   }

   return output.ToString();
}

And on using the base controller

public class MyController: BaseController
{
//ToHtml(...);
}

Problem

I am trying to use the accepted answer from this question. It seems that it will be exactly what i am looking for, but i have a problem. I don't know how to actually call it. This is what i have so far: First i am copying the code from the solution i mentioned: ``` public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext) { var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null); StringWriter output; using (output = new StringWriter()) { var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output); result.View.Render(viewContext, output); result.ViewEngine.ReleaseView(controllerContext, result.View); } return output.ToString(); } ``` This is what i have: ``` string viewToRender = "..."; int Data1 = ...; int Data2 = ...; System.Web.Mvc.ViewDataDictionary viewData = new System.Web.Mvc.ViewDataDictionary(); viewData.Add("Data1",Data1); viewData.Add("Data2",Data2); string html = ToHtml(viewToRender, viewData, ?????)//Here is my problem. ``` What should i pass in the controllerContext parameter?

Original source

Related problems