list of nullable bool values is always nulls

懵懂的女人 提交于 2020-01-14 06:16:06

问题


I have a partial view. In my partial a few properties are nullable boolean. If I check or uncheck the checkbox it is always null when I save the this record. What should I do if I want it to return false when check to uncheck and true when uncheck to check, otherwise null?

Here is the Entity class:

    public string Description { get; set; }
    [Required]
    public string DocType { get; set; }
    [Display(Name = "User")]
    [Required]
    public int Key { get; set; }
    [Display(Name = "Path")]
    public string Name { get; set; }
    public bool? ShowFullWidth { get; set; }
    public List<DmFormDefDTO> DmFormDefItems { get; set; }
    public bool? IsEnabled { get; set; }

Here is my partial view:

  if (Model.DmFormDefItems != null)
        {
<div class="main-body">
    <div id="container-body">
        <table class="table table-bordered table-striped" id="ordertable">
            <thead>
                <tr>

                    <th>Enabled
                    </th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.DmFormDefItems.Count; i++)
                {
                    <tr class="OrderDetailRow">
                        <td>
                            @if (Model.DmFormDefItems.ElementAt(i).ShowFullWidth == true)
                            {
                                @Html.CheckBoxFor(m => m.DmFormDefItems[i].ShowFullWidth.HasValue) <label>Show Full Width Page</label>    
                            }
                            else
                            {
                                @Html.CheckBoxFor(m => m.DmFormDefItems[i].ShowFullWidth.HasValue) <label>Show Full Width Page</label>                                            
                            }
                        </td>
                        <td>
                            @if (Model.DmFormDefItems.ElementAt(i).IsEnabled == true)
                            {
                                @Html.CheckBoxFor(m => m.DmFormDefItems[i].IsEnabled.HasValue)     
                            }
                            else
                            {
                                @Html.CheckBoxFor(m => m.DmFormDefItems[i].IsEnabled.HasValue)        
                            }
                        </td>
                    </tr>              
                }
            </tbody>
        </table>

回答1:


the checkbox can only have a true or false state. when handling bool? i use a dropdown list (NULL / True / False)

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

    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> property, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(property, 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 = new List<SelectListItem>()
        {
            new SelectListItem() { Text = BooleanTypeFor.Yes, Value = "True", Selected = (value.HasValue && value.Value == true) },
            new SelectListItem() { Text = BooleanTypeFor.No, Value = "False", Selected = (value.HasValue && value.Value == false) }
        };

        return htmlHelper.DropDownListFor(property, items, htmlAttributes ?? new { });
    }
}



回答2:


Firstly you not binding to your boolean property, your binding to its HasValue property which is a readonly property of Nullable<T> (refer documentation) which means it cannot be set when you post back, so the value in your controller will always be the default null value.

A checkbox only has 2 states (true or false) but a Nullable<bool> has 3 states (true or false or null) so there is no way a Nullable<bool> can be represented using a checkbox input.

3 possible options

  1. Use @Html.EditorFor(m => m.yourNullableBool) which will generate a dropdown with 3 values ("True", "False" and "Not Set")
  2. Use 3 radio buttons bound to your Nullable<bool> property with the values true, false and null
  3. Develop you own html helper and jquery plugin


来源:https://stackoverflow.com/questions/29749499/list-of-nullable-bool-values-is-always-nulls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!