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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay