![](/img/trans.png)
[英]How do i create a metadataId for a custom class derived from OrganizationRequest?
[英]How do I test for a custom class derived from Attribute in a template page?
所以我創建了一個自定義屬性,用於裝飾 StepViewModels。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class WizardStepAttribute : Attribute
{
public String Name { get; set; }
//public virtual int? Order { get; set; }
}
[PropertiesMustMatch("Email","ConfirmEmail")]
[WizardStep(Name="Preparer's Information")]
public class Step0ViewModel : IStepViewModel
{...
在我的 IStepViewModel.cshtml 中,我想顯示 WizardStep 屬性名稱(如果存在)。
這是我自己想要發生的事情的假裝代碼......
@Html.Label(ViewModel.ModelMetaData.Properties("WizardStep").Name)
執行此操作的正確方法是實現自定義 model 元數據提供程序,以根據屬性將元數據添加到 model:
public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<System.Attribute> attributes, System.Type containerType, System.Func<object> modelAccessor, System.Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var wizardStepAttr = attributes.OfType<WizardStepAttribute >().FirstOrDefault();
if (wizardStepAttr != null)
{
metadata.AdditionalValues.Add("WizardStep", wizardStepAttr);
}
return metadata;
}
}
...然后從 model 元數據中提取該數據:
@Html.Label(((WizardStepAttribute)ViewModel.ModelMetaData.AdditionalValues["WizardStep"]).Name)
您必須像這樣在Application_Start
中注冊此元數據提供程序:
ModelMetadataProviders.Current = new MyModelMetadataProvider();
(請注意,如果將ModelMetadataProvider
綁定到MyModelMetadataProvider
,MVC 的一些 DI 框架擴展會自動將其連接起來)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.