2016-10-05 45 views
0

我在我的模型有一个为空的布尔ASP.NET MVC 5可空布尔的下拉 - 参数

public bool? Property { get; set; } 

而且我通过EditorFor

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

使其我如何添加form-control类呈现选择和如何本地化字符串Not set,TrueFalse?或者更好的我怎样才能用自定义字符串来替换它们

+0

,除非你想创建你自己的模板(内置到源代码这就是)你不能改变的值。哪个版本的MVC? (您只能在MVC-5.1 +中使用'EditorFor()'添加html属性) –

+0

大概5.2.3 '' – Kicker

+1

在这种情况下'@ Html.EditorFor(m => m.Property,new {htmlAttributes = new {@class =“form-control”}})''。但是如果你想要自定义字符串,你需要创建一个自定义的'EditorTemplate',或者使用'DropDownListFor()',其中'SelectList'包含3个可能的值。 –

回答

1
@Html.DropDownListFor(m => m.Property, new SelectList(new[] 
       { 
        new SelectListItem { Value = null, Text = "Not set" }, 
        new SelectListItem { Value = false, Text = "False" }, 
        new SelectListItem { Value = true, Text = "True" }, 
       }, 
       "Value", 
       "Text" 
       ), 
     new { @class = "form-control" }) 
+1

为什么在世界上,你使用'new SelectList()'从第一个创建了第二个相同的'IEnumerable '(这是没有意义的额外开销)? –

+0

并参阅Jaimin Dave的回答评论 –

+0

您是对的。我编辑我的答案 –

0
You can try with below code: 

     @Html.DropDownListFor(m => m.Property, 
        new List<SelectListItem>(){      
        new SelectListItem { Value = "False", Text = "False" }, 
        new SelectListItem { Value = "True", Text = "True" } 
    },"Not set",new { @class = "form-control" }) 
+2

这也行不通。该属性是'bool?',所以'value'属性需要是'null','true'和'false'(不是'0'和'1') –

+0

这就对了!编辑。 –

+0

然后删除第三个''Select“'参数(有2个'null'选项没有意义) –