Skip to content

Instantly share code, notes, and snippets.

@secretorange
Last active February 17, 2019 16:23
Show Gist options
  • Save secretorange/1b31690c7f5ce8f435ae55f1b3f06789 to your computer and use it in GitHub Desktop.
Save secretorange/1b31690c7f5ce8f435ae55f1b3f06789 to your computer and use it in GitHub Desktop.
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
Copy link

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