我使用UIHint 派生属性将属性从视图模型传递到编辑器模板,我昨天才了解了精彩的IMetadataAware 界面1。
请注意对基本构造函数的调用如何强制我编写的编辑器模板的名称,特别是为了将属性作为参数添加到实际的帮助器中。传递给UIHint 参数的KnownUiHints.SelectionOther 常量等于“SelectionOtherInput”,即编辑器模板的名称。
帮助器参数随后可用于帮助器代码。
例如我的DropDownAttribute 使用以下代码传达属性:
public class SelectionOtherInputAttribute : UIHintAttribute, IMetadataAware
{
public SelectionOtherInputAttribute(string selectionElementName) : base(KnownUiHints.SelectionOther, KnownPresentationLayers.Mvc)
{
SelectionElementName = selectionElementName;
}
public SelectionOtherInputAttribute(string selectionElementName, object otherSelectionKey) : base(KnownUiHints.SelectionOther, KnownPresentationLayers.Mvc)
{
SelectionElementName = selectionElementName;
ControlParameters[SelectionOtherInputControlParameterKeys.OtherSelectionKey] = otherSelectionKey;
}
public string SelectionElementName { get; set; }
public object OtherSelectionKey { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["@OtherSelectionAttrinbuteNames.SelectionElementName"] = SelectionElementName;
metadata.AdditionalValues["@OtherSelectionAttrinbuteNames.OtherSelectionKey"] = OtherSelectionKey;
}
}
这是我的SelectionOtherInput 编辑器模板。
@using OtherInput.Core
@{
var meta = ViewData.ModelMetadata.AdditionalValues;
var selectionElementName = (string)meta["@OtherSelectionAttrinbuteNames.SelectionElementName"];
var otherSelectionKey = meta["@OtherSelectionAttrinbuteNames.OtherSelectionKey"];
var inputElementname = ViewData.TemplateInfo.HtmlFieldPrefix;
}
@Html.SelectionOtherTextBoxFor(m => Model, selectionElementName, otherSelectionKey.ToString())
然后我在视图模型中使用我的属性如下:
[SelectionOtherInput("EmploymentStatusId", 1)]
public string OtherEmploymentStatus { get; set; }
这会导致OtherEmploymentStatus 由SelectionOtherInput 编辑器模板呈现,而后者又会呈现我的SelectionOtherTextBoxFor 助手,并将属性作为参数传递。