9

Whats the best way to print out "Yes" or "No" depending on a value

In my view I want to print out

Model.isStudent

and I dont want True or False, I want Yes or No.... do I Have to write if else statement?

3 Answers 3

11

Write a helper method:

public static class MyExtensions
{
    public static string FormatBool(this HtmlHelper html, bool value)
    {
        return html.Encode(value ? "Yes" : "No");
    }
}

And use it like this:

<%= Html.FormatBool(Model.IsStudent) %>
Sign up to request clarification or add additional context in comments.

Comments

6

How about an extension method on bool:

public static class BoolExtensions {
    public static string ToYesNo(this bool value) {
        return value ? "Yes": "No";
    }
}

Usage would be:

Model.isStudent.ToYesNo();

Comments

4

MVC 4: This example shows in detail the implementation of boolean templates for a dropdownlist that contains Yes, No and Not Set values and also handles null bool values. Inspired from Darin Dimitrov and Jorge - Thank you.

Model Student.cs

[Display(Name = "Present:")]
[UIHint("YesNo")]
public bool? IsPresent { get; set; }

DisplayTemplates: YesNo.cshtml

@model Nullable<bool>

@if (Model.HasValue)
{
    if (Model.Value)
        { <text>Yes</text> }
    else
        { <text>No</text> }
}
else
    { <text>Not Set</text> }

EditorTemplates: YesNo.cshtml

@model Nullable<bool>

@{
    var listItems = new[]
    {   
        new SelectListItem { Value = "null", Text = "Not Set" },
        new SelectListItem { Value = "true", Text = "Yes" },
        new SelectListItem { Value = "false", Text = "No" }
    };  
}

@if (ViewData.ModelMetadata.IsNullableValueType)
{
    @Html.DropDownList("", new SelectList(listItems, "Value", "Text", Model))
}
else
{
    @Html.CheckBox("", Model.Value)
}

View:

  <div class="editor-label">
        @Html.LabelFor(model => model.IsPresent )
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.IsPresent )
        @Html.ValidationMessageFor(model => model.IsPresent )
    </div>

1 Comment

Side note : If you want to yes/no all your bools without using the UIHint, name the template files boolean.cshtml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.