MVC地图模型可空布尔 [英] MVC map to nullable bool in model

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

问题描述

使用含有该领域的视图模型:

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

无法隐式转换类型'布尔?以布尔。一个显式转换存在(是否缺少强制转换?)

我试过铸造,并使用 .value的和既不工作。

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

请注意,我想的行为是提交表单应该设置 ISDEFAULT 在模型为真或假。 的值只是意味着模型尚未填充。

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.

推荐答案

的问题是,你真的有三种可能的值;真,假,空,这样的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).

布拉德·威尔逊讨论在他的博客<一href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html\">here.他用可能为空的布尔一个DropDownList。

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

这StackOverflow的<一个href=\"http://stackoverflow.com/questions/2490790/why-is-checkboxfor-producing-runtime-error\">question确实描述的情况比我上面做了一个更好的工作。的缺点的解决方案有时可空并不意味着假的,它应该是可空。这方面的一个例子是过滤标准,你不希望真的还是假的应用。

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地图模型可空布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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