Last active
October 21, 2022 12:23
-
-
Save pauldotknopf/b424e9b8b03d31d67f3cce59f09ab17f 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(); | |
} | |
} | |
} |
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
Hi @BIJINPALAKKAL you need to create a NullView file like this https://github.com/nopSolutions/nopCommerce/blob/develop/src/Presentation/Nop.Web.Framework/Controllers/NullView.cs
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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