开发者

How do I test for a custom class derived from Attribute in a template page?

开发者 https://www.devze.com 2023-03-16 15:23 出处:网络
So I created a custom Attribute that I will used to decorate StepViewModels. [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号