Skip to content

Instantly share code, notes, and snippets.

@pauldotknopf
Last active October 21, 2022 12:23
Show Gist options
  • Save pauldotknopf/b424e9b8b03d31d67f3cce59f09ab17f to your computer and use it in GitHub Desktop.
Save pauldotknopf/b424e9b8b03d31d67f3cce59f09ab17f to your computer and use it in GitHub Desktop.
Render .NET Core ASP.NET MVC ViewComponent to string from controller
public class HomeController : Controller
{
public async Task<string> RenderViewComponent(string viewComponent, object args)
{
var sp = HttpContext.RequestServices;
var helper = new DefaultViewComponentHelper(
sp.GetRequiredService<IViewComponentDescriptorCollectionProvider>(),
HtmlEncoder.Default,
sp.GetRequiredService<IViewComponentSelector>(),
sp.GetRequiredService<IViewComponentInvokerFactory>(),
sp.GetRequiredService<IViewBufferScope>());
using (var writer = new StringWriter())
{
var context = new ViewContext(ControllerContext, NullView.Instance, ViewData, TempData, writer, new HtmlHelperOptions());
helper.Contextualize(context);
var result = await helper.InvokeAsync(viewComponent, args);
result.WriteTo(writer, HtmlEncoder.Default);
await writer.FlushAsync();
return writer.ToString();
}
}
}
@sefacan
Copy link

sefacan commented Mar 29, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment