Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 1 year ago 127
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 Source

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

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


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().


@Html.Raw(User.Identity.IsAuthenticated ? "<div>Support</div>" : "Contact Us")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download