MVC DropDownListFor default value for bool

血红的双手。 提交于 2019-12-13 17:05:58

问题


I have a dropdownlistfor with True/False values. I want the default value to be true. Right now it's false because the default of a bool is false. This dropdown sometimes gets created dynamically in javascript so I can't set the value in the model before it gets passed. How do I set the default to True in the chtml file?

Thank you.

//----------  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; }
      ...
}

//--------------- Browser Source ----------------------- True False


回答1:


@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"}
        )


来源:https://stackoverflow.com/questions/23610941/mvc-dropdownlistfor-default-value-for-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!