Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 可为空布尔值的复选框_Asp.net Mvc 3_Razor_Nullable - Fatal编程技术网

Asp.net mvc 3 可为空布尔值的复选框

Asp.net mvc 3 可为空布尔值的复选框,asp.net-mvc-3,razor,nullable,Asp.net Mvc 3,Razor,Nullable,我的模型有一个布尔值,它必须为null public bool? Foo { get; set; } 所以在我的cshtml中 @Html.CheckBoxFor(m => m.Foo) 但那不起作用。也不能用(bool)来铸造它。如果我这样做 这不会创建错误,但在发布时它不会绑定到我的模型,并且foo设置为null。在页面上显示Foo并将其绑定到帖子上的模型的最佳方式是什么?我过去也遇到过类似的问题 在HTML中创建一个复选框输入,并设置属性name=“Foo”,这应该仍

我的模型有一个布尔值,它必须为null

public bool? Foo
{
   get;
   set;
}
所以在我的cshtml中

@Html.CheckBoxFor(m => m.Foo)
但那不起作用。也不能用(bool)来铸造它。如果我这样做


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

我过去也遇到过类似的问题

在HTML中创建一个复选框输入,并设置属性name=“Foo”,这应该仍然可以正常发布

<input type="checkbox" name="Foo" checked="@model.Foo.Value" /> Foo Checkbox<br />
Foo复选框
我的模型有一个布尔值,它必须为null

public bool? Foo
{
   get;
   set;
}
为什么??这没有道理。复选框有两种状态:选中/未选中,如果愿意,则为真/假。没有第三国

或者等等,您正在视图中使用域模型而不是视图模型?那是你的问题。因此,我的解决方案是使用视图模型,在该模型中定义一个简单的布尔属性:

public class MyViewModel
{
    public bool Foo { get; set; }
}
现在,您将让您的控制器操作将此视图模型传递给视图,并生成相应的复选框。

我使用了它

@Html.EditorFor(model => model.Foo) 
然后在Views/Shared/EditorTemplates/Boolean.cshtml中创建一个文件,其中包含以下内容:

@model bool?

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

使用隐藏字段使原语复杂化,以明确不建议使用False还是Null

复选框不是您应该使用的——它实际上只有一种状态:选中了。否则,它可能是任何东西

当数据库字段为可空布尔值(
bool?
)时,用户体验应使用3个单选按钮,其中第一个按钮表示“已选中”,第二个按钮表示“未选中”,第三个按钮表示您的空值,无论空值的语义如何。您可以使用
下拉列表来保存不动产,但用户必须单击两次,而且选择几乎不是即时清晰的

  1     0      null 
True  False  Not Set
Yes   No     Undecided
Male  Female Unknown
On    Off    Not Detected
RadioButtonList定义为名为RadioButtonForSelectList的扩展,它为您构建单选按钮,包括选定/选中的值,并设置
,以便您可以使用css使单选按钮水平(显示:内联块)、垂直或以表格方式(显示:内联块;宽度:100px;)

在模型中(我使用string,string作为字典定义的教学示例。您可以使用bool?,string)

public IEnumerable Sexsli{get;set;}
SexDict=新字典()
{
{“M”,“男性”},
{“F”,“女性”},
{“U”,“待定”},
};
//将字典类型转换为SelectListItem类型
Sexsli=SexDict.Select(k=>
新建SelectListItem
{
选定=(k.Key==“U”),
Text=k.值,
Value=k.Key.ToString()
});
我是一个
@RadioButtonForSelectList(m=>m.Sexsli,Model.Sexsli,“Sex”)
@Html.ValidationMessageFor(m=>m.Sexsli)
公共静态类
{
公共静态MvcHtmlString RadioButtonForSelectList(
这个HtmlHelper HtmlHelper,
表情表情,
IEnumerable值列表,
字符串rbClassName=“水平”)
{
var metaData=modelmetada.FromLambdaExpression(表达式,htmlHelper.ViewData);
var sb=新的StringBuilder();
if(listOfValues!=null)
{
//为列表中的每个项目创建一个单选按钮
foreach(在listOfValues中选择ListItem项)
{
//生成要给单选按钮字段的id
var id=string.Format(“{0}{1}”,metaData.PropertyName,item.Value);
//使用现有html帮助程序创建并填充单选按钮
var label=htmlHelper.label(id,HttpUtility.HtmlEncode(item.Text));
var radio=String.Empty;
如果(item.Selected==true)
{
radio=htmlhelp.RadioButtonFor(表达式,item.Value,new{id=id,@checked=“checked”}).ToHtmlString();
}
其他的
{
radio=htmlHelper.RadioButtonOn(表达式,item.Value,new{id=id}).ToHtmlString();
}//创建html字符串以返回到客户端浏览器
//例如,选择1
sb.AppendFormat(“{0}{1}”,收音机,标签,rbClassName);
}
}
返回MvcHtmlString.Create(sb.ToString());
}
}

我有
bool?在模型中禁用{get;set;}
。在视图中插入

<div class="inputClass" id="disabled">
    <div>
    @if(Model.IsDisabled==null)
    {
        Model.IsDisabled = false;
    }           
    @Html.CheckBoxFor(model => model.IsDisabled.Value)         
    </div>
</div> 

@if(Model.IsDisabled==null)
{
Model.IsDisabled=false;
}           
@CheckBoxFor(model=>model.IsDisabled.Value)

对我来说,解决方案是更改视图模型。考虑你正在寻找发票。这些发票可以付款也可以不付款。所以你的搜索有三种选择:付费、无偿或“我不在乎”

我最初把它设定为布尔?字段:

public bool? PaidInvoices { get; set; }
这使我无意中发现了这个问题。我最终创建了一个枚举类型,并按如下方式处理:

@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.NotSpecified, new { @checked = true })
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.Yes) 
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.No)

当然,我把它们包在标签中并指定了文本,我的意思是这里还有另外一个选项要考虑。

复选框只给你提供2个值(真,假)。Nullable boolean有3个值(true、false、null),因此不可能通过复选框来实现

一个好的选择是使用下拉列表

模型


这是一个古老的问题,现有的答案描述了大多数备选方案。但是有一个简单的选择,如果你有布尔?在viewmodel中,并且您不关心UI中的null:

@Html.CheckBoxFor(m => m.boolValue ?? false);

只需检查null值并返回false即可:

@{ bool nullableValue = ((Model.nullableValue == null) || (Model.nullableValue == false)) ? false : true; }
@Html.CheckBoxFor(model => nullableValue)

我也面临同样的问题。我尝试了以下方法来解决这个问题 因为我不想更改数据库,然后再次生成EDMX

@{

   bool testVar = (Model.MYVar ? true : false);

 }

<label>@Html.CheckBoxFor(m => testVar)testVar</label><br />
@{
bool testVar=(Model.MYVar?true:false);
}
@Html.CheckBoxFor(m=>testVar)testVar

在类似的问题中找到了答案-。 它非常简单,而且非常有效:

@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")
这就像@afinkelstein接受的答案,只是我们不需要特殊的“编辑模板”

I wo
@Html.CheckBoxFor(m => m.boolValue ?? false);
@{ bool nullableValue = ((Model.nullableValue == null) || (Model.nullableValue == false)) ? false : true; }
@Html.CheckBoxFor(model => nullableValue)
@{

   bool testVar = (Model.MYVar ? true : false);

 }

<label>@Html.CheckBoxFor(m => testVar)testVar</label><br />
@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")
@using System.Globalization    
@using System.Web.Mvc.Html    
@model bool?

@{
    bool? myModel = false;
    if (Model.HasValue)
    {
        myModel = Model.Value;
    }
}

<input type="checkbox" checked="@(myModel)" name="@ViewData.TemplateInfo.HtmlFieldPrefix" value="True" style="width:20px;" />
@{  bool testVar = ((bool)item.testVar ? true : false); }
  @Html.DisplayFor(modelItem => testVar)
// Foo is still a nullable boolean.
public bool? Foo 
{
    get 
    { 
        if (FooIsNull)
            return null;

        return FooCheckbox;  
    }
    set
    {
        FooIsNull   = (value == null);
        FooCheckbox = (value ?? false);
    }
}

// These contain the value of Foo. Public only so they are visible in Razor views.
public bool FooIsNull { get; set; }
public bool FooCheckbox { get; set; }
@Html.HiddenFor(m => m.FooIsNull)

@if (Model.FooIsNull)
{
    // Null means "checkbox is hidden"
    @Html.HiddenFor(m => m.FooCheckbox)
}
else
{
    @Html.CheckBoxFor(m => m.FooCheckbox)
}
public static MvcHtmlString CheckBoxFor<T>(this HtmlHelper<T> htmlHelper, Expression<Func<T, bool?>> expression, IDictionary<string, object> htmlAttributes) {

    ModelMetadata modelMeta = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    bool? value = (modelMeta.Model as bool?);

    string name = ExpressionHelper.GetExpressionText(expression);

    return htmlHelper.CheckBox(name, value ?? false, htmlAttributes);
}
@helper CheckBoxFor(WebViewPage page, string propertyName, bool? value, string htmlAttributes = null)
{
    if (value == null)
    {
        <div class="checkbox-nullable">
            <input type="checkbox" @page.Html.Raw(htmlAttributes)>
        </div>
    }
    else if (value == true)
    {
        <input type="checkbox" value="true" @page.Html.Raw(htmlAttributes) checked>
    }
    else
    {
        <input type="checkbox" value="false" @page.Html.Raw(htmlAttributes)>
    }
}
@Helpers.CheckBoxFor(this, "IsPaymentRecordOk", Model.IsPaymentRecordOk)
.checkbox-nullable {
    border: 1px solid red;
    padding: 3px;
    display: inline-block;
}
        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool?>> expression)
        {
            return htmlHelper.CheckBoxFor<TModel>(expression, null);
        }
        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool?>> expression, object htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            bool? isChecked = null;
            if (metadata.Model != null)
            {
                bool modelChecked;
                if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked))
                {
                    isChecked = modelChecked;
                }
            }
            return htmlHelper.CheckBox(ExpressionHelper.GetExpressionText(expression), isChecked??false ,  htmlAttributes);
        }
public static SelectList GetBoolTriState()
{
    var items = new List<SelectListItem>
    {
        new SelectListItem {Value = "", Text = ""},
        new SelectListItem {Value = "True", Text = "Yes"},
        new SelectListItem {Value = "False", Text = "No"},
    };

    return new SelectList(items, "Value", "Text");
}
public NotNullFoo
{
    get { return this.Foo?? false; }
    set { this.Foo= (value == false ? null : true as bool?); }
}


public bool? Foo
{
   get;
   set;
}
  @Html.CheckBoxFor(x => Model.NotNullFoo })