mercredi 25 novembre 2020

Can you do an "if statement" within an html tag?

I have an Asp.net Core MVC application. In my _Layout.cshtml page I'm trying to create a link on the nav bar to create a new ad. I would like that if the user is logged in, they get taken to the page where they can create a new ad. Otherwise, if they are not logged in, they should be taken to a login page. The question basically is, can you use the @ sign within an html tag to type some c#. Here's what I want to do, but it's not valid code.

           <li class="nav-item">
                  <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                  <a class="nav-link text-dark" asp-area="" asp-controller="Home" 
                     @if(User.Identity.IsAuthenticated)
                     {
                          asp-action="NewAd"
                     }
                     else
                     {
                          asp-action="LogIn"
                     }>
                  New Ad</a>
           </li>

Even better would be to do the shorthand version of an if statment somehow, ie:

(User.Identity.IsAuthenticated ? asp-action="NewAd" : asp-action="LogIn")

Is there any way to achieve this without duplicating the tag inside an if/else?

Aucun commentaire:

Enregistrer un commentaire