Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is an old thread but still at the top of some searches.</p> <p>You could do this by using the built in DropDownListFor HTML Helper:</p> <pre><code> &lt;%= Html.DropDownListFor(model =&gt; Model.MyBooleanProperty,new List&lt;SelectListItem&gt;(){ new SelectListItem(){ Text = "Yes", Value="True"}, new SelectListItem(){ Text = "No", Value="False"}})%&gt; </code></pre> <p>You can also implement your own HTML Helper:</p> <pre><code> public static MvcHtmlString BooleanDropdownListFor&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression) { return BooleanDropdownListFor(htmlHelper, expression, null); } public static MvcHtmlString BooleanDropdownListFor&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, string EmptyText) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); bool? value = null; if (metadata != null &amp;&amp; metadata.Model != null) { if (metadata.Model is bool) value = (bool)metadata.Model; else if (metadata.Model.GetType() == typeof(bool?)) value = (bool?)metadata.Model; } List&lt;SelectListItem&gt; items = EmptyText != null ? new List&lt;SelectListItem&gt;() { new SelectListItem() { Text = EmptyText, Value = "" }, new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue &amp;&amp; value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue &amp;&amp; value.Value == false) } } : new List&lt;SelectListItem&gt;() {new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue &amp;&amp; value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue &amp;&amp; value.Value == false) } }; return htmlHelper.DropDownListFor(expression, items); } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload