I've created a new MVC6 project and building a new site. The goal is to get the rendered result of a view. I found the following code, but I can't get it to work because I can't find the ControllerContext
and the ViewEngines
.
Here is the code I want to rewrite:
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
The released dotnet core 1.0 has changed, this version of the above code works with 1.0 RTM.
These usings are required for this code to compile:
I also had to add a DI interfaces to the controller constructor:
My account constructor looks like this now:
Solution by Martin Tomes works well. My changes: removed serviceProvider and get ICompositeViewEngine in constructor via DI. Constructor looks like:
and put
instead of
First of all we can leverage the built in dependency injection that comes with ASP.Net MVC Core which will give us the
ICompositeViewEngine
object we need to render our views manually. So for example, a controller would look like this:Next, the code we actually need to render a view. Note that is is now an
async
method as we will be making asynchronous calls internally:And to call the method, it's as simple as this:
The solution provided by Martin Tomes worked for me but I had to replace:
with
Also in controller constructor had to add