4

I'm trying to wrap up repeating HTML chunks in ASP MVC Core 2.1 using ViewComponents.

Tag helpers make it seemingly easy:

<vc:expansion-panel title="Headline">
    content.....
</vc:expansion-panel>

However: The inner HTML of the tag is not rendered. RenderBody() obviously is not the appropriate function here. So what function should be used?

Since I haven't found any references online, probably I got the wrong idea about ViewComponents. However, even if so, I would still see no reason why not to render inner HTML into the ViewComponent.

Qestion: How to render the Inner HTML of <vc:expansion-panel>... in the ViewComponent?


@addTagHelper *, ProjectName

ExpansionPanelViewComponent.cs

using Microsoft.AspNetCore.Mvc;

namespace ProjectName.Components
{
    public class ExpansionPanelViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke(string title)
        {
            ViewData["Title"] = title;
            return View();
        }
    }
}

Default.cshtml

<h2 class="panel">@ViewData["Title"]</h2>
<div class="panel">
    @RenderBody()            <----- ??
</div>
bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • 1
    Possible duplicate of [In a view component invoked as a tag helper, how can we access the inner HTML?](https://stackoverflow.com/questions/50889261/in-a-view-component-invoked-as-a-tag-helper-how-can-we-access-the-inner-html) – Kirk Larkin Nov 27 '18 at 11:19
  • The @RenderBody call specifies where the content of a view will be displayed in the layout. You can't use it anywhere else. – Lewis86 Nov 27 '18 at 11:22
  • Duplicate? Yes. But the question is left rather unanswered. The OP marked it as answered only because he found a workaround. – bytecode77 Nov 27 '18 at 12:08
  • What you want to render is that display the content in the tag helper on the default page? AFAIK, it is unlikely. The content in the default page will overwrite the contents of the tag helper. Unless the content is used as a parameter to the tag helper as mentioned in the link above – Xueli Chen Nov 28 '18 at 12:00

0 Answers0