DEV Community

Uthman Rahimi
Uthman Rahimi

Posted on

3 1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more