1

Are there any html helper methods for displaying boolean values in a dropdown?

1
  • What html do you expect? A select element with option items that has true or false as value? Commented Jan 27, 2010 at 17:06

5 Answers 5

13

This is an old thread but still at the top of some searches.

You could do this by using the built in DropDownListFor HTML Helper:

 <%= Html.DropDownListFor(model => Model.MyBooleanProperty,new List<SelectListItem>(){ new SelectListItem(){ Text = "Yes", Value="True"}, new SelectListItem(){ Text = "No", Value="False"}})%>

You can also implement your own HTML Helper:

    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return BooleanDropdownListFor(htmlHelper, expression, null);

    }
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string EmptyText)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        bool? value = null;

        if (metadata != null && metadata.Model != null)
        {
            if (metadata.Model is bool)
                value = (bool)metadata.Model;
            else if (metadata.Model.GetType() == typeof(bool?))
                value = (bool?)metadata.Model;
        }

        List<SelectListItem> items = EmptyText != null ?
            new List<SelectListItem>() { new SelectListItem() { Text = EmptyText, Value = "" }, new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } } :
            new List<SelectListItem>() {new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } };

        return htmlHelper.DropDownListFor(expression, items);
    }

I suggest using a nullable bool property on your View Model so that the dropdown does not default to "false" or "true". You can easily markup the viewmodel with the Required attribute which would handel if no option was selected.

Sign up to request clarification or add additional context in comments.

Comments

2

Why not use Html.CheckBox()?

2 Comments

Technically you cannot produce null values with a check box. If the semantics of the situation require an "I don't know" possibility, then you need another method. But otherwise this is the right way to go. Or maybe Html.CheckBox(x => x.Property).
@NickLarsen, Although I agree, the OP specifically asked about bools. And unless it's nullable (not stated), this isn't a problem.
2

Use the DropDownListFor helper. Pass in your boolean value and a select list containing values that you want to map back to boolean.

Model.MyBooleanList might be a selectlist with selectlistitems {("Yes",true);("No",false)} Model.MyBoolean is just a bool value that you want to attain/set on your view

<%= Html.DropDownListFor(m => m.MyBoolean, Model.MyBooleanList)%>

hth

Comments

0

I have this:

public static class BoolUtility
{
    public static IEnumerable<SelectListItem> SelectList(string defaultText = null, string defaultTrue = "True", string defaultFalse = "False")
    {
        var list = new List<SelectListItem>
        {
            new SelectListItem {Text = defaultTrue, Value = "True"},
            new SelectListItem {Text = defaultFalse, Value = "False"}
        };

        if (defaultText != null)
        {
            list.Insert(0, new SelectListItem
            {
                Text = defaultText,
                Value = string.Empty
            });
        }

        return list;
    }
}

And use it like this:

@Html.DropDownListFor(m => m.SomeBoolProperty, BoolUtility.SelectList("All", "Yes", "No"))

And it seems to work well. Pretty flexible, since you can control all of the labels, and whether or not there is a 'default' value.

Oh, and some NUnit unit tests, if you like. By no means comprehensive, but this isn't that complicated...

[TestFixture]
class BoolUtilityTests
{
    [Test]
    public void Parameterless()
    {
        var actual = BoolUtility.SelectList().ToList();
        Assert.That(actual.Count, Is.EqualTo(2));
        Assert.That(actual.First().Text, Is.EqualTo("True"));
        Assert.That(actual.First().Value, Is.EqualTo("True"));
        Assert.That(actual.Last().Text, Is.EqualTo("False"));
        Assert.That(actual.Last().Value, Is.EqualTo("False"));
    }

    [Test]
    public void LabelOverrides()
    {
        var actual = BoolUtility.SelectList(defaultTrue: "Yes", defaultFalse: "No").ToList();
        Assert.That(actual.Count, Is.EqualTo(2));
        Assert.That(actual.First().Text, Is.EqualTo("Yes"));
        Assert.That(actual.First().Value, Is.EqualTo("True"));
        Assert.That(actual.Last().Text, Is.EqualTo("No"));
        Assert.That(actual.Last().Value, Is.EqualTo("False"));
    }

    [Test]
    public void IncludeDefaultOption()
    {
        var actual = BoolUtility.SelectList(defaultText: "all").ToList();
        Assert.That(actual.Count, Is.EqualTo(3));
        Assert.That(actual.First().Text, Is.EqualTo("all"));
        Assert.That(actual.First().Value, Is.EqualTo(string.Empty));
    }
}

Comments

0

if you want to capture YES, NO and NOTSET (no answer) kinda values i would suggest you use a dropdown list like this

Public Class MyModelClass
{
  [Display(Name = "Project Based Subsidy?")]
  public Nullable<bool> IsSubsidyProjectBased{ get; set; }

  public SelectList DropDownItems
  {
      get
      {
          List<DropDownItems> ddItem = new List<DropDownItems>();
          ddItem.Add(new DropDownItems("--Select--", null));
          ddItem.Add(new DropDownItems("Yes", true));
          ddItem.Add(new DropDownItems("No", false));                
          return new SelectList(ddItem, "Value", "Text");
      }
  }

public class DropDownItems
{
    public DropDownItems(string text, bool? value)
    {
        this.Text = text;
        this.Value = value;
    }
    public string Text { get; set; }
    public bool? Value { get; set; } 
}

}

Then in your View you can simply have

@Html.DropDownListFor(model => model.IsSubsidyProjectBased, Model.DropDownItems)

Comments

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.