DEV Community

Uthman Rahimi
Uthman Rahimi

Posted on

Render html tags based on condition in asp.net core

If you are using Razor in your applications based on ASP.NET CORE, sometimes you might want to check something and according to that generate HTML tags and show them to clients. For example one of the common things is when we check to know if a user is logged-in or not, if User is not logged-In we would show the Login button otherwise show the Sign-out button.
To accomplish this, we end up with a code like this:

if (User.Identity.IsAuthenticated)
{
    <a href="/Account/Signout">SignOut</a>
}
else {
<a href="/Account/SignIn">SignIn</a>
}
Enter fullscreen mode Exit fullscreen mode

This is fine and does what we want, but there is one more way that I think is much more cleaner and that is using Tag Helper.
After implementing a custom Tag Helper, we can refactor our code and render HTML tags like below:

<a href="/Account/Signout" condition=="@User.Identity.IsAuthenticated">SignOut</a>
Enter fullscreen mode Exit fullscreen mode

As you can see above, there is no if statement and just used condition in HTML tag and passed it a boolean value.

Implementation of Condition tag helper is:


 using Microsoft.AspNetCore.Razor.TagHelpers;

namespace CustomTagHelpers.TagHelpers
{
    [HtmlTargetElement(Attributes = nameof(Condition))]
     public class ConditionTagHelper : TagHelper
    {
        public bool Condition { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (!Condition)
            {
                output.SuppressOutput();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

To make this tag helpe available throughout all views, add its namespace to _ViewImports.cshtml

Condition tag helper renders output when passed a true value.

Discussion (0)