Skip to main content

ASP.NET Conditional Anchor Tag Helper

Get rid of if/else statements in you Razor.

Tag helpers are a handy new feature in ASP.NET 5. They allow you to write semantic markup.

Here's a handy Conditional Anchor Tag Helper that will omit the anchor tag if the href is null or empty.

Life Before TagHelper

@if (!String.IsNullOrWhiteSpace(Model.Url))
{
    <a href="@Model.Url"><img src="image.jpg" /></a>
}
else
{
    <img src="image.jpg" />
}

Life After TagHelper

<a asp-conditional href="@Model.Url"><img src="image.jpg" /></a>

Code

Only a few lines are required.

namespace SecretOrange
{
    [HtmlTargetElement("a", Attributes = "asp-conditional")]
    public class ConditionalAnchorTagHelper : TagHelper
    {
        public override async void Process(TagHelperContext context, TagHelperOutput output)
        {
            var href = context.AllAttributes["href"]?.Value.ToString();

            if (String.IsNullOrWhiteSpace(href))
            {
                output.SuppressOutput();

                var childContent = await output.GetChildContentAsync();
                output.Content.SetHtmlContent(childContent);
            }
            else
            {
                output.Attributes.Remove(output.Attributes["asp-conditional"]);
            }
        }
    }
}

Code on GitHub

Hello, my name's Lee and I work as a full-stack web developer specialising in Microsoft ASP.NET technologies. I love using Umbraco and also MANAGED, my own interal CMS.

Contact me at lee.gunn@secretorange.co.uk

All skills

Contact

Get in touch to talk about your project or just ask me a question.

lee.gunn@secretorange.co.uk

Skype: lee_gunn