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

Render ViewComponent inside html string


Lets say I have a ViewComponent named MyComponent.

As of ASP.NET Core 1.1 I can render this ViewComponent by writing this inside a razor view .cshtml page:

 <vc:my-component></vc:my-component>

I want to do something like this:

@{string myHtml = "<vc:my-component></vc:my-component>";}

@(new HtmlString(myHtml))

I installed and tried RazorEngine by doing this, but this did not work:

string template = "<vc:my-component></vc:my-component>";
var result = Engine.Razor.RunCompile(template, "messageTemplateKey", null, new { Name = "some model data" });
ViewBag.result = result;

then in the .chtml file:

 @(new HtmlString(ViewBag.result))

The backstory to this is that I've created a ViewComponent with some logic on how to handle image files, now I want to search and replace all img tags in some html with my ViewComponent. Before I do that I need to make sure this even works.


Solution

  • This is what I ended up doing:

    I moved the view code from the Default.cshtml for MyComponent to a partial view (_myPartial). Then I used a IViewRenderService inspired by this post.

    Then I could render and get my html string after passing in the viewmodel by doing this:

     var result = ViewRenderService.RenderToString("_myPartial", viewModel);