Search code examples
c#asp.net-corerazor-pagesasp.net-core-viewcomponent

How can I access the content within the tags in an ASP.NET CORE ViewComponent?


I create a ViewComponent that renders some HTML on a Razor page. Looks like this:

<vc:Blockheader button-text="Create new skill" block-title="@ViewData["Title"]">
    hello
</vc:Blockheader>

How do I access the value hello from the ViewComponent class?


Solution

  • You don't have access to this content. The parameters to the view component are passed as attributes (in lower kebab case) so you can add an additional parameter to Invoke method.

    Example:

    public class BlockHeader : ViewComponent
    {
        public IViewComponentResult Invoke(string buttonText, string blockTitle, string message)
        {
            // ...
            return View<string>(message);
        }
    }
    

    Invoking a view component as a Tag Helper:

    <vc:block-header button-text="param1Value" block-title="param2Value" message="hello">    
    </vc:block-header>