Search code examples
c#asp.net-coreasp.net-core-tag-helpers

ASP.NET Core TagHelper with content from ViewBag - it's empty


I have a simple ToastTagHelper:

[HtmlTargetElement("toast")]
public class ToastTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        string message = output.Content.GetContent();
        if (string.IsNullOrWhiteSpace(message))
        {
            output.TagName = "";    // this should not output anything!
            return;
        }

        output.TagName = "div";
        output.Attributes.Add("id", "toast");
        output.Content.SetContent(message.Trim());
    }
}

Now, here's how I use it in my _Layout:

<toast>@ViewBag.Message</toast>

And I initialize ViewBag.Message in my Controller when I need it. The problem is even it's initialized I get the following:

[message text]

NO TAGS here. I put a breakpoint and here's what happens - when it hits Process method, the Content is still empty. And then later somewhere down the pipe it initializes the content from ViewBag but it's too late.

So, how can I make it work?


Solution

  • For this to work I had to override ProcessAsync instead of Process and call await output.GetChildContentAsync() in place of output.Content.GetContent().