Ever wonder if there’s another way to rewrite if
block statement in razor?
Adding a TagHelper can help you transform the if
block statement into this:

[HtmlTargetElement("*", Attributes = "[asp-if]")]
public class IfTagHelper : TagHelper
{
/// <summary>
/// Shows the element when this condition is true
/// </summary>
[HtmlAttributeName("asp-if")]
public bool IsTrue { get; set; } = true;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!IsTrue)
{
output.TagName = null;
output.Content.Clear();
}
}
}
Simply replace asp-if
to any attribute name you want. Gist: https://gist.github.com/bingzer/78852e67ec4320a0b9d9381b109230fa
Leave a Reply