Skip to content

Instantly share code, notes, and snippets.

@pauldotknopf
Last active October 21, 2022 12:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • 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();
}
}
}
@Bujart85
Copy link

Hi Paul, nice work there!! I've been trying to return a ViewController using jQuery for almost 3 days now and I've been looking around everywhere for a solution until I came very close with yours.
With your code I have only been able to render the results when I returned a content from the ViewComponent return Content("Test content"); but I wasn't able to render the view that I need: return View(educations) not working. How can I make it work by returning a ViewComponent with a model inside?

P.S. I'm quite new in web development

@BIJINPALAKKAL
Copy link

Its doesn't work on dot net core 3.1.
NullView.Instance can't be accessed here. Since in 3.1, NullView.Instance is no longer public. It is now an internal class.
Any alternative in 3.1. Please help. It's blocking my upgrade

@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