I have a ToString()
method for Partial Views.
My usings :
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Threading.Tasks;
public static class ViewExtensions
{
public static async Task<string> ToString(this PartialViewResult partialView, ActionContext actionContext)
{
using (var writer = new StringWriter())
{
var services = actionContext.HttpContext.RequestServices;
var executor = services.GetRequiredService<PartialViewResultExecutor>();
var view = executor.FindView(actionContext, partialView).View;
var viewContext = new ViewContext(actionContext, view, partialView.ViewData, partialView.TempData, writer, new HtmlHelperOptions());
await view.RenderAsync(viewContext);
return writer.ToString();
}
}
}
In ASP.NET Core 2.2 I am getting this error :
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.PartialViewResultExecutor' has been registered. at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
Add the following line in your ConfigureServices
method of the Startup
class:
services.AddSingleton<PartialViewResultExecutor>();