所以我创建了一个自定义属性,用于装饰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)
答案 0 :(得分:1)
执行此操作的正确方法是实现自定义模型元数据提供程序,以根据属性向模型添加元数据:
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;
}
}
...然后从模型元数据中提取数据:
@Html.Label(((WizardStepAttribute)ViewModel.ModelMetaData.AdditionalValues["WizardStep"]).Name)
您必须在Application_Start
中注册此元数据提供程序,如下所示:
ModelMetadataProviders.Current = new MyModelMetadataProvider();
(请注意,如果将ModelMetadataProvider
绑定到MyModelMetadataProvider
),MVC的某些DI Framework扩展会自动将其连接起来