MVC在模型中映射到可空bool [英] MVC map to nullable bool in model

查看:221
本文介绍了MVC在模型中映射到可空bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

包含以下字段的视图模型:

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) %>

不能将类型bool?隐式转换为bool。有一个明确的转换(你错过了一个演员?)

我试过转换,并使用 .Value 并没有工作。

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

请注意,我希望的行为是提交表单应设置 IsDefault 在模型中为真或假。值 null 只是意味着模型尚未填充。

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.

推荐答案

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

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在他的博客上讨论了这里。他使用一个DropDownList可空的布尔值。

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

这个StackOverflow 问题比描述事情做得更好。解决方案的缺点有时可以为空,并不意味着虚假,它应该是空的。一个例子是过滤条件,您不希望使用true或false。

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.

这篇关于MVC在模型中映射到可空bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆