不建议使用隐藏字段来复杂化原始代码以澄清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使单选按钮水平(display: inline-block),垂直或以表格方式显示(display: inline-block; width:100px;)。
在模型中(我正在使用字符串,字符串作为示例来说明字典定义。您可以使用bool?,string)。
public IEnumerable<SelectListItem> Sexsli { get; set; }
SexDict = new Dictionary<string, string>()
{
{ "M", "Male"},
{ "F", "Female" },
{ "U", "Undecided" },
};
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)
{
foreach (SelectListItem item in listOfValues)
{
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
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();
}
sb.AppendFormat("<div class=\"RB{2}\">{0}{1}</div>", radio, label, rbClassName);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}