I have ASP.NET 4.6 Web-Forms and ASP.NET Core websites. And there is a class Library project which is shared amongst them. My purpose is to include the Master Page related stuff into the View Component that resides into the Class Library.
I have created the master page View Component in the Class Library, and successfully able to invoke it into the shared _Layout view of ASP.NET Core website. Below is the blog which I followed for it.
Reusing External View Components
My next task is to somehow get the flatten HTML of the master page View Component from the Class Library into the ASP.NET 4.6 web forms. I read couple of stack overflow questions, and came across the following one, which shows how to render the Razor View to string in ASP.NET Core.
Render Razor View to string in ASP.NET Core
Here is the code snippet from the answer, and I can confirm that, it works fine, provided I put this code in the Controller class of the ASP.NET Core.
public string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ActionContext.ActionDescriptor.Name;
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
var engine = Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
ViewEngineResult viewResult = engine.FindPartialView(ActionContext, viewName);
ViewContext viewContext = new ViewContext(ActionContext, viewResult.View,
ViewData, TempData, sw, new HtmlHelperOptions());
var t = viewResult.View.RenderAsync(viewContext);
t.Wait();
return sw.GetStringBuilder().ToString();
}
}
My plan is to move this code into the Class Library project. But, if you see the dependencies, it needs Resolver (IServiceProvider
) which is the public property available in the base class (Microsoft.AspNet.Mvc.Controller).
My question is how can I inject the Resolver or the Razor View Engine from ASP.NET Core into the Class Library project. So that, when ASP.NET 4.6 Web-Forms requests the flatten HTML for the View Component, the Class Library serves it hassle free.