MVC DropDownList为bool的默认值

时间:2014-05-12 13:53:10

标签: asp.net-mvc boolean dropdownlistfor

我有一个带有True / False值的下拉列表。我希望默认值为true。现在它是假的,因为bool的默认值是假的。此下拉列表有时会在javascript中动态创建,因此我无法在模型传递之前设置该值。如何在chtml文件中将默认值设置为True?

谢谢。

//----------  cshtml file ---------------
...
   <td class="valuebool">
        @Html.DropDownListFor(m => m.IsBoolFilterCondition, 
        new SelectList(
            new[]
            {
                // The following two lines defaulted to false
                //new { Value = "true", Text = "True" },
                //new { Value = "false", Text = "False" },

                // The next two lines also defaulted to false
                //new SelectListItem { Value = "true", Text = "True", Selected = true },
                //new SelectListItem { Value = "false", Text = "False", Selected = false },

                // The following two lines also default to false
                new { Value = "true", Text = "True", Selected = true },
                new { Value = "false", Text = "False", Selected = false },                    
            },
            "Value",
            "Text"
            ),
            new { @class="valuebool"}
        )
...

//------- Model Class ------------------------
public class FilterCondition
{
      ...
      public bool IsBoolFilterCondition { get; set; }
      ...
}

// ---------------浏览器来源-----------------------     真正     假

1 个答案:

答案 0 :(得分:4)

@Html.DropDownListFor(m => m.IsBoolFilterCondition, 
        new SelectList(
            new[]
            {
                new SelectListItem { Value = "1", Text = "True" ,Selected = true},
                new SelectListItem { Value = "0", Text = "False" },
            },
            "Value",
            "Text"
            ),
            new { @class="valuebool"}
        )