Question

I have a bit field in database which I want to display on my HTML view as "Yes" or "No" How can I use ternary(?:) operator to do this?

Here is what I have, but it displays "No" for all the records.

<%= Html.Encode( Convert.ToString(item.IsValid) == "True" ? "Yes" : "No")%>
Était-ce utile?

La solution

There are two ways to fix this.

1) Seems how IsValid is already a boolean, just take the value

<%= item.IsValid ? "Yes" : "No"%>

2) If you insist on converting it, compare it using Equals with the StringComparison.InvariantCultureIgnoreCase flag

<%= Convert.ToString(item.IsValid).Equals("True", StringComparison.InvariantCultureIgnoreCase) ? "Yes" : "No"%>

Autres conseils

or even simpler -

<%= Html.Encode(item.IsValid ? "Yes" : "No") %>

Normally you can use below :

<%: item.IsValid ? "Yes" : "No" %>

This will fix your issue.

Why are you converting to string? This should just work assuming IsValid is a bool:

<%= Html.Encode(item.IsValid) == true ? "Yes" : "No")%>

If it's a string you'd want something like:

<%= Html.Encode(item.IsValid.ToLower() == "true" ? "Yes" : "No")%>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top