0

問題是我想在asp.net mvc3中創建一個自定義模型字段屬性,需要訪問其他模型字段。命名爲「PersonId」。如何訪問自定義模型字段屬性中的其他模型字段?

所以我有這樣

public class PersonWoundModel : IAppointmentModel 
    { 

     public int PersonId { get; set; } 

     [CustomAttribute("PersonId")] 
     public FillInList Positions { get; set; } 
} 

模型和我自定義屬性

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] 
    public class CustomAttribute : Attribute, IMetadataAware 
    { 
     public int PersonId { get; private set; } 


     public CustomAttribute(bool allowDelete, bool allowEdit, string htmlHelpers) 
     { 
      //i need to get a PersonId here somehow.. reflection or any other method. 
     } 
} 

所以basicaly我需要得到[CustomAttribute] aPersonId領域進一步使用。我想着使用反射,但不知道如何獲得模型對象。謝謝很多幫助人。

回答

0

你不能 - 因爲沒有模型對象。

您的屬性在元數據中是「序列化的」 - 即構建它的字段是序列化的,所以它們必須是編譯時間已知文字。當你使用像GetCustomAttributes這樣的方法在你的模型類上使用反射時,構造函數將被調用。但是在那個時候,你(在你的代碼中)可能會有一些對象需要處理。

+0

是否有可能以某種方式獲取模型對象? – Mindaugas

+0

正如我所說 - 不,並且在構造函數中有?:)? - 正如我所說的,當你在模型的類型上使用反射時,它會被調用。如果您非常需要*任何*對象 - 只需使用'new' – Bond

+0

構建一個屬性即可在任何模型中的任何位置使用該屬性。我不需要任何對象:)我需要那個PersonId是:)。我的意思是有可能在屬性類中的任何位置獲取模型對象:) – Mindaugas

相關問題