可为空布尔值的复选框 [英] Checkbox for nullable boolean

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

问题描述

我的模型有一个必须可以为空的布尔值

My model has a boolean that has to be nullable

public bool? Foo
{
   get;
   set;
}

所以在我的 Razor cshtml 中有

so in my Razor cshtml I have

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

除此之外不起作用.也不会用 (bool) 投射它.如果我这样做

except that doesn't work. Neither does casting it with (bool). If I do

@Html.CheckBoxFor(m => m.Foo.Value)

这不会产生错误,但在发布时它不会绑定到我的模型并且 foo 设置为 null.在页面上显示 Foo 并使其绑定到我的模型的最佳方式是什么?

that doesn't create an error, but it doesn't bind to my model when posted and foo is set to null. Whats the best way to display Foo on the page and make it bind to my model on a post?

推荐答案

我得到了它

@Html.EditorFor(model => model.Foo) 

然后在 Views/Shared/EditorTemplates/Boolean.cshtml 使用以下内容制作文件:

and then making a file at Views/Shared/EditorTemplates/Boolean.cshtml with the following:

@model bool?

@Html.CheckBox("", Model.GetValueOrDefault())

这篇关于可为空布尔值的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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