Skip to content

Instantly share code, notes, and snippets.

@yigith
Forked from pauldotknopf/HomeController.cs
Created December 25, 2019 13:52
Show Gist options
  • Save yigith/b0ba14cec2f2f1c00bfd2977fb26fa0d to your computer and use it in GitHub Desktop.
Save yigith/b0ba14cec2f2f1c00bfd2977fb26fa0d 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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment