使用编辑器模板处理可空类型
本文关键字:类型 处理 编辑器 | 更新日期: 2023-09-27 18:11:08
我开发了一个编辑器模板,它采用布尔类型并创建了一个下拉列表,以将true
和false
的默认值更改为Si
和No
。现在,当我部署应用程序时,我没有意识到boolean
和Nullable<boolean>
是一样的,并且对我的编辑器模板(boolean.cshtml)的名称有影响。现在我不想这样,我想修改editorfor
的行为,只有当模型的数据类型是Nullable<boolean>
而不是布尔值时。我该如何处理??
@model Nullable<bool>
@{
var listItems = new[]
{
new SelectListItem { Value = "true", Text = "Si" },
new SelectListItem { Value = "false", Text = "No" }
};
}
@Html.DropDownListFor( model => model.Value, listItems)
你不能阻止他们使用相同的编辑器模板。但是您可以在编辑器模板中处理它。你有:
ViewData.ModelMetadata.IsNullableValueType
如果您阅读了本文,您实际上可以看到默认模板是如何在两种不同的呈现之间进行切换的。就偷吧:
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.htmlMy Views/Shared/EditorTemplates/Boolean。CSHTML是双向的,处理可空的和常规的复选框。
@model bool?
@{
if (ViewData.ModelMetadata.IsNullableValueType)
{
<text><div class="RB"></text>
Dictionary<string, object> yesAttrs = new Dictionary<string, object>();
Dictionary<string, object> noAttrs = new Dictionary<string, object>();
Dictionary<string, object> nullAttrs = new Dictionary<string, object>();
yesAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes");
noAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No");
nullAttrs.Add("id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA");
if (Model.HasValue && Model.Value)
{
yesAttrs.Add("checked", "checked");
}
else if (Model.HasValue && !Model.Value)
{
noAttrs.Add("checked", "checked");
}
else
{
nullAttrs.Add("checked", "checked");
}
@Html.RadioButtonFor(x => x, "true", yesAttrs)
<label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label>
@Html.RadioButtonFor(x => x, "false", noAttrs)
<label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label>
@Html.RadioButtonFor(x => x, "", nullAttrs)
<label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))NA" class="nostrong" title="Unknown or To Be Determined">tbd</label>
@:</div>
}
else
{
ModelState state = ViewData.ModelState[ViewData.ModelMetadata.PropertyName];
bool value = Model ?? false;
if (state != null && state.Errors.Count > 0)
{
<div class="input-validation-error" style="float: left"></div>
}
else
{
@Html.CheckBox("", value)
}
}
}
下拉列表只有2-3个选择项是不考虑用户的;它们需要两次点击,而单选按钮只需要一次点击(除非你没有空间)。
当你的客户/用户还没有做出决定,不想做一个,不认为你知道答案是你的业务,或者需要取消设置true/1/on/positive
或false/0/off/negative
,因为两者都不准确,Nullable<boolean>
的第三个选项可以表示待定(tbd),未设置,未知,或不适用(n/a)。