Search code examples
c#asp.net-core-mvcasp.net-core-viewcomponent

Is it possible to execute a ViewComponent inside a controller and store the HTML as a string


I currently have several view components that are used in many different places. I would like to be able to store the resulting HTML that is generated when calling a view component into a string variable so that i can use the HTML for other purposes (such as email).

I have looked at a questions and posts but haven't been able to find one that does what I am looking for. I currently have the ViewComponentResult stored to use but the ExecuteResult() returns void so unable to use that.

I would expect to be able to manipulate the view component result to execute which will then return the HTML that would be sent to the browser to display. then i could use that as an email body. However i am currently no closer to getting the HTML without knowing a full path to the resulting view


Solution

  • I was able to find a method that did exactly what i needed (get the returned HTML as a string) as described in one of the answers in this post.

    The code block that i used was..

    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.
      }
    }
    

    This image shows the variable that gets returned during debug