Home > Back-end >  C# asp.net single line else less if
C# asp.net single line else less if

Time:12-29

<h3><%= User.Identity.IsAuthenticated ? true : User.Identity.Name; %></h3>

I'd like to write a one-line code that returns the member's name when the member is already logged in. But the IsAuthenticated code already returns true, so do i need to use true ? Also, I don't want to do anything unless user not logged in. in this case. When you want to write concise code in one line. Which code would be best?

CodePudding user response:

You can use a conditional operator which has the form:

condition ? consequent : alternative

In your case this would be:

<h3><%= User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty; %></h3>

CodePudding user response:

you can use this <h3>@(User.Identity.IsAuthenticated ? User.Identity.Name :"")</h3>

CodePudding user response:

There is a better way that you can do this, By using Tag helper which explained in this article, you can rewrite your code like this:

<h3 condition="User.Identity.IsAuthenticated">
  User.Identity.Name
</h3>

Condition tag helper implementation 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();
            }
        }
    }
}
  • Related