MVC 映射到模型中可为 null 的 bool

发布于 2024-09-05 04:20:37 字数 398 浏览 5 评论 0原文

对于包含字段的视图模型:

public bool? IsDefault { get; set; }

尝试在视图中映射时出现错误:

<%= Html.CheckBoxFor(model => model.IsDefault) %>

无法隐式转换类型“bool?” '布尔'。存在显式转换(您是否缺少强制转换?)

我尝试过强制转换,并使用 .Value 但都不起作用。

请注意,我想要的行为是提交表单应将模型中的 IsDefault 设置为 true 或 false。 null 值仅表示模型尚未填充。

With a view model containing the field:

public bool? IsDefault { get; set; }

I get an error when trying to map in the view:

<%= Html.CheckBoxFor(model => model.IsDefault) %>

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

I've tried casting, and using .Value and neither worked.

Note the behaviour I would like is that submitting the form should set IsDefault in the model to true or false. A value of null simply means that the model has not been populated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

多情癖 2024-09-12 04:20:37

问题是你确实有三个可能的值; true、false和null,所以CheckBoxFor不能处理这三种状态(只能处理两种状态)。

Brad Wilson 在他的博客上讨论

这个 StackOverflow 问题 在描述情况方面比我上面做的要好得多。该解决方案的缺点是有时可以为空并不意味着错误,它应该可以为空。例如,您不希望应用 true 或 false 的过滤条件。

The issue is you really have three possible values; true, false and null, so the the CheckBoxFor cannot handle the three states (only two states).

Brad Wilson discusses on his blog here. He uses a DropDownList for nullable booleans.

This StackOverflow question does a much better job of describing the situation than I did above. The downside to the solution is sometimes nullable does not imply false, it should be nullable. An example of this would be filter criteria where you don't want true or false applied.

眼中杀气 2024-09-12 04:20:37

如果您不关心 null 值,并且只想在其为 null 时取消选中该复选框,则可以执行以下操作:

在模型中创建另一个 bool 类型的属性,如下所示:

public bool NotNullableBool
{
    get
    {
        return NullableBool == true;
    }
    set
    {
        NullableBool = value;
    }
}

然后只需使用它进行绑定...

If you don't care about the null value, and just want the checkbox to be unchecked when its null, you can do the following:

Create another property of type bool in your Model like this:

public bool NotNullableBool
{
    get
    {
        return NullableBool == true;
    }
    set
    {
        NullableBool = value;
    }
}

Then just use that for binding...

七秒鱼° 2024-09-12 04:20:37

对我来说,这要好得多:

<%= Html.CheckBox("IsDefault", Model.IsDefault.HasValue? Model.IsDefault : false) %>

To me, this is a lot better:

<%= Html.CheckBox("IsDefault", Model.IsDefault.HasValue? Model.IsDefault : false) %>
南笙 2024-09-12 04:20:37

以下是如何在 DropDownListFor 中映射可布尔布尔 bool? 属性:

@model SomeModel

<!-- ...some HTML... -->

@Html.DropDownListFor(m => m.NullableBooleanProperty, new SelectList(
        new[] { 
            new { Value = "", Text = "-- Choose YES or NO --" },
            new { Value = "true", Text = "YES" },
            new { Value = "false", Text = "NO" },
        },
        "Value",
        "Text"
    ))

以下是如何使用 将其映射到 CheckBoxFor不可为 null 的代理属性作为解决方法:

在 ViewModel 中:

public bool NullableBooleanPropertyProxy
{
    get
    {
        return NullableBooleanProperty == true;
    }
    set
    {
        NullableBooleanProperty = value;
    }
}

在视图中:

@model SomeModel

<!-- ...some HTML... -->

@Html.CheckBoxFor(m => m.NullableBooleanPropertyProxy)

此解决方法的唯一缺点是 null 值将被视为 false:如果不能接受,最好使用可以支持三种状态的控件,例如前面提到的 DropDownListFor

有关详细信息,请阅读

Here's how to map a bullable boolean bool? property in a DropDownListFor:

@model SomeModel

<!-- ...some HTML... -->

@Html.DropDownListFor(m => m.NullableBooleanProperty, new SelectList(
        new[] { 
            new { Value = "", Text = "-- Choose YES or NO --" },
            new { Value = "true", Text = "YES" },
            new { Value = "false", Text = "NO" },
        },
        "Value",
        "Text"
    ))

And here's how to map it to a CheckBoxFor by using a non-nullable proxy property as a workaround:

In the ViewModel:

public bool NullableBooleanPropertyProxy
{
    get
    {
        return NullableBooleanProperty == true;
    }
    set
    {
        NullableBooleanProperty = value;
    }
}

In the View:

@model SomeModel

<!-- ...some HTML... -->

@Html.CheckBoxFor(m => m.NullableBooleanPropertyProxy)

The only downside of this workaround is that the null value will be treated as false: if you can't accept that, it's better to use a control that can support three states, such as the aforementioned DropDownListFor . 

For further info, read this post on my blog.

眼趣 2024-09-12 04:20:37

要添加到 vapcguy 答案,另一种更“干净”的方法如下

@Html.CheckBox("IsDefault", Model?.IsDefault)

<%= Html.CheckBox("IsDefault", Model?.IsDefault) %>

To add to vapcguy answer, another more "cleaner" way to do it is like follows

@Html.CheckBox("IsDefault", Model?.IsDefault)

Or

<%= Html.CheckBox("IsDefault", Model?.IsDefault) %>
無處可尋 2024-09-12 04:20:37

您可以创建一个编辑器模板来呈现可为空布尔值的复选框。将模板命名为 Boolean.cshtml 以将其用作站点内所有布尔属性的默认值。确保该文件位于文件夹 ~/Views/Shared/EditorTemplates 中

@model bool?
@Html.CheckBox(String.Empty, Model??false)

You can create an editor template to render a checkbox for nullable Booleans. Name the template Boolean.cshtml to use it as the default for all of the Boolean properties within the site. Ensure that the file is in the folder ~/Views/Shared/EditorTemplates

@model bool?
@Html.CheckBox(String.Empty, Model??false)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文