Nullable布尔值下拉列表的编辑器模板未呈现

use*_*721 3 c# asp.net-mvc-3

我有一个称为Critical的属性,它是一个可空的Bool,例如“ Critical”位为null,存储在表中。用户可以选择“是/否”或“空白”(将值存储为NULL)

我在Shared / EditorTemplates中创建了一个名为FriendlyBool.cshtml的Editor模板。

@model bool? 
@using System.Web.Mvc   
@{   
    var selectList = new List<SelectListItem>();  
    selectList.Add(new SelectListItem { Text = "", Value = "" }); 
    selectList.Add(new SelectListItem { Text = "Yes", Value = "true", Selected = Model.HasValue && Model.Value }); 
    selectList.Add(new SelectListItem { Text = "No", Value = "false", Selected = Model.HasValue && !Model.Value });
 } 
Run Code Online (Sandbox Code Playgroud)

我认为我将此编辑器模板称为

 <div class="bodyContent">
        <span class="leftContent">
            @Html.Label("Critical")
        </span><span class="rightContent">
         @Html.EditorFor(model => model.critical, "FriendlyBool")
        </span>
    </div>
Run Code Online (Sandbox Code Playgroud)

运行视图时,我看到默认下拉列表,其值为“未设置”,“正确”和“假”,为什么我的编辑器模板不显示?

Ant*_*onK 6

将答案从alireza扩展为满足htmlAttributes的传递:

@model bool?
@{
    var selectList = new List<SelectListItem>
    {
        new SelectListItem {Text = "(Any)", Value = String.Empty, Selected = !Model.HasValue},
        new SelectListItem {Text = "Yes", Value = "true", Selected = Model.HasValue && Model.Value},
        new SelectListItem {Text = "No", Value = "false", Selected = Model.HasValue && !Model.Value}
    };
}
@Html.DropDownListFor(m => m, selectList, ViewData["htmlAttributes"])
Run Code Online (Sandbox Code Playgroud)

用法:

@Html.EditorFor(model => model.critical, new
{
    htmlAttributes = new { @class = "variables-filter", disabled = "disabled" }
})
Run Code Online (Sandbox Code Playgroud)


小智 5

EditorTemplate没有生成任何 html(只是创建一个SelectList)。将模板更改为

@model bool? 
@using System.Web.Mvc   
@{   
    var selectList = new List<SelectListItem>();  
    selectList.Add(new SelectListItem { Text = "Yes", Value = "true" }); 
    selectList.Add(new SelectListItem { Text = "No", Value = "false" });
} 
@Html.DropDownListFor(m => m, selectList, "")
Run Code Online (Sandbox Code Playgroud)

还要确保您的财产没有该[Required]属性。

旁注

  1. 使用DropDownListFor()接受 a的重载labelOption 来生成null选项
  2. 不需要设置 的Selected属性SelectListItem。您绑定到一个属性,因此如果值为 if null,则将选择第一个选项,或者如果它true的第二个选项(“是”)将被选择。