Reputation: 34152
I'm Migrating an old website to ASP.Net MVC 5, I had a link like this:
<a href="/contact"><%=User.Identity.IsAuthenticated?"Support":"Contact Us"%></a>
I googled and tried several things and I ended up with the following code:
<a href="/contact">@if{User.Identity.IsAuthenticated){@Html.Raw("Support");}else{@HtmlRaw("Contact Us");}</a>
But this seems not to be the solution as it is much more complicated than the first one, while Razor is created for the simplicity
Upvotes: 1
Views: 2250
Reputation: 1973
Just wrapping your ternary expression in @()
should work.
<a href="/contact">@(User.Identity.IsAuthenticated ? "Support" : "Contact Us")</a>
Edit:
If you need HTML elements, you can wrap your ternary expression in @Html.Raw()
.
i.e.
@Html.Raw(User.Identity.IsAuthenticated ? "<div>Support</div>" : "Contact Us")
Upvotes: 5
Reputation: 26312
I think this one is more readable.
@if(User.Identity.IsAuthenticated){
<a href="/contact">Support</a>
}
else{
<a href="/contact">Contact Us</a>
}
Upvotes: 0
Reputation: 2793
The operator you are referring to is called the ternary operator, it is used to have inline if statements
In your example, it can be used like so
<a href="/contact">@(User.Identity.IsAuthenticated ? "Support" : "Contact Us")</a>
Upvotes: 1