Reputation: 85
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?
Upvotes: 0
Views: 4068
Reputation: 76
You cannot nest razor views inside html tags. But, I can see based on your requirements you need to redirect the user to the login page if he hasn't registered yet. For that you can:
@if(!User.Identity.IsAuthenticated){
//if user is not authenticated return the page with
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="LogIn"></a>
}
else{
//if user is authenticated return the page with
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="NewAd"></a>
}
Upvotes: 2
Reputation: 72
You need to put the code in a script tag.
<script>if(User.Identity.IsAuthenticated)
{
asp-action="NewAd"
}
else
{
asp-action="LogIn"
} </script>
Upvotes: -1