So I created a custom Attribute that I will used to decorate StepViewModels.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class WizardStepAttribut开发者_C百科e : Attribute
{
public String Name { get; set; }
//public virtual int? Order { get; set; }
}
[PropertiesMustMatch("Email","ConfirmEmail")]
[WizardStep(Name="Preparer's Information")]
public class Step0ViewModel : IStepViewModel
{...
In my IStepViewModel.cshtml I want to display the WizardStep property name if it exists.
Here is my own pretend code for what I want to happen...
@Html.Label(ViewModel.ModelMetaData.Properties("WizardStep").Name)
The correct way to do this is to implement a custom model metadata provider to add metadata to the model based on the attribute:
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;
}
}
... then pull that data from the model metadata:
@Html.Label(((WizardStepAttribute)ViewModel.ModelMetaData.AdditionalValues["WizardStep"]).Name)
You will have to register this metadata provider in Application_Start
like so:
ModelMetadataProviders.Current = new MyModelMetadataProvider();
(Note that some DI Framework extensions for MVC automatically wire this up if you bind ModelMetadataProvider
to MyModelMetadataProvider
)
精彩评论