-
-
Save yigith/b0ba14cec2f2f1c00bfd2977fb26fa0d to your computer and use it in GitHub Desktop.
Render .NET Core ASP.NET MVC ViewComponent to string from controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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