问题
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