If you’re using Razor Pages, you might have noticed that you can’t nest TagHelpers. This is because Razor Pages are not using the same TagHelper infrastructure as Razor Views.
I recently stumbled upon this problem when I was trying to nest a TagHelper inside another TagHelper. I refactored and svg icon behind a TagHelper, and wanted to use it inside another TagHelper which I was using to display alerts similar to what we know as alerts in Twitter Bootstrap.
In my Razor Page, I had the following code initially:
How I wanted my front-end code to look like:
I figured, we might wanted to use the svg icon in other places as well, so I decided to extract it into a TagHelper.
The BaseAlertIcon would essentially serve to toggle the styling of the svg icon based on the ColorVariant enum with values we know as:
Primary
Secondary
Success
Danger
Warning
Info
The DangerAlertIcon would inherit from the BaseAlertIcon and would set the Variant property to ColorVariant.Danger by default. Now for normal icons, we wouldn’t want to set it here, but that’s an entirely different debate.
In our BaseAlertIcon, we’ve specified we wanted to create a custom HTML tag for an SVG icon. Now inside our implementation below, we will have to append the content to set the content of the SVG icon.
Now we can use our DangerAlertIcon inside our DangerAlertBox. We will have to use the HtmlTargetElement attribute to specify the HTML tag we want to use for our DangerAlertBox.
So below, we’ll folow again a similar approach defining BaseAlertBox which will serve as a base class for our DangerAlertBox. We will define a Variant property which will be of type ColorVariant. We will also define a Message property which will be of type string. We will also define a Class property which will be of type string. This will allow us to add custom classes to our DangerAlertBox.
We need to use a new TagHelperOutput instance to render our icon.
And that’s it, we can now use our DangerAlertBox inside our Razor Page, which is directly using our DangerAlertIcon.
Now the code for DangerAlertBox is fairly straightforward. I always define a constant for each tag helper, so I can easily reference to it in my Razor Page or my other tag helpers, as we’re seeing below: