不推荐使用带有隐藏字段的原语来阐明是 False 还是 Null。
复选框不是你应该使用的——它实际上只有一种状态:选中。否则,它可能是任何东西。
当您的数据库字段为可空布尔值 (bool?) 时,UX 应使用 3 单选按钮,其中第一个按钮代表您的“已选中”,第二个按钮代表“未选中”,第三个按钮代表您的null,无论 null 的语义是什么意思。您可以使用<select><option> 下拉列表来节省空间,但用户必须单击两次,并且选择不会立即清晰。
1 0 null
True False Not Set
Yes No Undecided
Male Female Unknown
On Off Not Detected
RadioButtonList,定义为一个名为 RadioButtonForSelectList 的扩展,为您构建单选按钮,包括选中/选中的值,并设置 <div class="RBxxxx">,以便您可以使用 css 使您的单选按钮变为水平状态(显示:inline-块)、垂直或表格形式(显示:inline-block;宽度:100px;)
在模型中(我使用字符串,字符串作为字典定义作为教学示例。你可以使用 bool?,字符串)
public IEnumerable<SelectListItem> Sexsli { get; set; }
SexDict = new Dictionary<string, string>()
{
{ "M", "Male"},
{ "F", "Female" },
{ "U", "Undecided" },
};
//Convert the Dictionary Type into a SelectListItem Type
Sexsli = SexDict.Select(k =>
new SelectListItem
{
Selected = (k.Key == "U"),
Text = k.Value,
Value = k.Key.ToString()
});
<fieldset id="Gender">
<legend id="GenderLegend" title="Gender - Sex">I am a</legend>
@Html.RadioButtonForSelectList(m => m.Sexsli, Model.Sexsli, "Sex")
@Html.ValidationMessageFor(m => m.Sexsli)
</fieldset>
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues,
String rbClassName = "Horizontal")
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = String.Empty;
if (item.Selected == true)
{
radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id, @checked = "checked" }).ToHtmlString();
}
else
{
radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
}// Create the html string to return to client browser
// e.g. <input data-val="true" data-val-required="You must select an option" id="RB_1" name="RB" type="radio" value="1" /><label for="RB_1">Choice 1</label>
sb.AppendFormat("<div class=\"RB{2}\">{0}{1}</div>", radio, label, rbClassName);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}