Update: I'm updating this to work with .Net Core 2.x as the APIs have changed since 2015!
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:
public class MyController : Controller
{
private ICompositeViewEngine _viewEngine;
public MyController(ICompositeViewEngine viewEngine)
{
_viewEngine = viewEngine;
}
//Rest of the controller code here
}
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:
private async Task<string> RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.ActionDescriptor.ActionName;
ViewData.Model = model;
using (var writer = new StringWriter())
{
ViewEngineResult viewResult =
_viewEngine.FindView(ControllerContext, viewName, false);
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
ViewData,
TempData,
writer,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return writer.GetStringBuilder().ToString();
}
}
And to call the method, it's as simple as this:
public async Task<IActionResult> Index()
{
var model = new TestModel
{
SomeProperty = "whatever"
}
var renderedView = await RenderPartialViewToString("NameOfView", model);
//Do what you want with the renderedView here
return View();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…