Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 20 days ago 7
ASP.NET (C#) Question

?: condition in Razor C#

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

Answer

Just wrapping your ternary expression in @() should work.

<a href="/contact">@(User.Identity.IsAuthenticated ? "Support" : "Contact Us")</a>

Edit:

I'm editing my answer with what I wrote in my comment. Just to let anyone else who needs HTML elements instead of plain text know, you can wrap your ternary expression in @Html.Raw().

i.e.

@Html.Raw(User.Identity.IsAuthenticated ? "<div>Support</div>" : "Contact Us")
Comments