Html helper for boolean values in asp.net mvc
Are there any html helper methods for disp开发者_StackOverflow中文版laying boolean values in a dropdown?
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.
Why not use Html.CheckBox()?
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
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));
}
}
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)
精彩评论