skip to Main Content
<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?

3

Answers


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

    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
  3. 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();
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search