2011-07-01 17 views
0

StepViewModelsをデコレートするために使用するカスタム属性を作成しました。私IStepViewModel.cshtmlでテンプレートページの属性から派生したカスタムクラスをテストするにはどうすればよいですか?

[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 
{... 

私はそれが存在する場合WizardStepプロパティ名を表示したいです。ここで

は、これを行うための正しい方法は、上のベースモデルにメタデータを追加するためのカスタムモデルのメタデータプロバイダを実装することである

@Html.Label(ViewModel.ModelMetaData.Properties("WizardStep").Name)

答えて

1

...私は起こるしたいもののために私自身のふりコードです属性:

@Html.Label(((WizardStepAttribute)ViewModel.ModelMetaData.AdditionalValues["WizardStep"]).Name) 

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; 
    } 
} 

は...その後、モデルのメタデータからそのデータをプルあなたがそうのようなApplication_Startで、このメタデータプロバイダを登録する必要があります

ModelMetadataProviders.Current = new MyModelMetadataProvider(); 

(あなたがMyModelMetadataProviderModelMetadataProviderをバインドする場合は、これを自動的にアップ配線MVCのためのいくつかのDIフレームワークの拡張ことに注意してください)

+0

を私から何を返しますかそのCreateMetaDataメソッド? –

+0

@Doug Chamberlain:申し訳ありませんが、中断しました。私の更新された答えを見てください。 – StriplingWarrior

+0

偉大な答え。私は1つの問題を抱えています。 'System.Attribute>の' attributes'Ienumerableコレクションには、WizardStepAttribute型の項目がないので、if条件は決して実行されません。 WizardStepAttributeアイテムをワイヤリングして属性変数に含めるにはどうすればよいですか? –

関連する問題