MVC model boolean display yes or no

66,417

Solution 1

In your view:

@(item.isTrue?"Yes":"No")

Solution 2

You could use a custom html helper extension method like this:

@Html.YesNo(item.IsTrue)

Here is the code for this:

public static MvcHtmlString YesNo(this HtmlHelper htmlHelper, bool yesNo)
{
    var text = yesNo ? "Yes" : "No";
    return new MvcHtmlString(text);
}

This way you could re-use it throughout the site with a single line of Razor code.

Solution 3

To expand on DigitalD's answer, you could consider wrapping this up in an extension method:

public static string ToFriendlyString(this Boolean b)
{
    return b ? "Yes" : "No";
}

Then you can use it all over the place:

@item.IsTrue.ToFriendlyString()

Solution 4

In your model write something like this:

public Nullable<bool> Active
{
    get;
    set;
}
public string ISActive
{
    get
    {
        return (bool)this.Active ? "Yes" : "NO";
    }
}

Active is a boolean property, we create ISActive property for reading its value and show appropriate message to user.

Solution 5

This is a little late, but...

One useful method missed by other answers answers is the Custom DisplayTemplate method. By putting this Code:

@model bool
<p>@{Model ? "Yes" : "No"}</p>

Into a Partial View (Maybe YesNo.cshtml) in the Display Templates folder (/Views/Shared/DisplayTemplates). Then, in your view, use this line:

@Html.Display(item.isTrue,"YesNo")

where "YesNo" is whatever you named your Partial View, minus the .cshtml extension.

By adding the second string (the templateName), you tell DisplayExtensions to display the boolean with your custom template, rather than the default method (a checkbox).

This method may not be the simplest for this situation, but it comes in handy with more complex situations (such as, say, a custom calendar for selecting dates)

Share:
66,417
Marco Dinatsoli
Author by

Marco Dinatsoli

Updated on November 21, 2020

Comments

  • Marco Dinatsoli
    Marco Dinatsoli over 3 years

    i have a boolean field in my model in mvc 4 entity framework 4.5

    i want to display the field in my view

    i use this call

    @item.isTrue
    

    but i got true or false,

    i want to get yes when true and no when false

    what should i do please?