Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET 5 Conditional Anchor Tag Helper. This tag helper will omit the anchor tag if the href is null or empty.

Example

🔥 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>
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"]);
}
}
}
}
@ikourfaln

This comment has been minimized.

Copy link

@ikourfaln ikourfaln commented Nov 8, 2016

hmmm useful Tag helper to prevent if..else... in Razor.
thanx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment