If block TagHelper

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: