6

我有以下UIHInt基於attibute:如何找到UIHInt屬性的目標屬性?

[AttributeUsage(AttributeTargets.Property)] 
public class DropDownListAttribute : UIHintAttribute, IMetadataAware 
{ 
    public DropDownListAttribute(string selectListName) 
     : base(KnownUiHints.DropDown, KnownPresentationLayers.Mvc, selectListName) 
    { 
     SelectListName = selectListName; 
    } 

    public string SelectListName { get; set; } 

    public void OnMetadataCreated(ModelMetadata metadata) 
    { 
     metadata.AdditionalValues[KnowMetadataKeys.SelectListName] = SelectListName; 
    } 
} 

它的目的是將的SelectList分配給單個值視圖模型屬性被從列表中選擇,如:

public class DemoModel: ViewModel 
{ 
    [Required] 
    [DropDownList("LanguageSelect")] 
    [Display(Name = "Language")] 
    public int? LanguageId { get; set; } 

    public SelectList LanguageSelect { get; set; } 
} 

我有這個工作現在與一些非常Golbergian機器和我自己的元數據提供商,但發現IMetadataAware.OnMetadataCreated,我覺得我可以簡化這一點。現在,我將SelectListName添加到元數據中,然後跳轉到a)將SelectList變成一種全局字典,並且b)在呈現下拉列表時從該字典中取出選擇列表。

我想將SelectList本身添加到屬性中的模型元數據中,即該屬性適用的屬性的本地元數據,但是如何訪問該屬性或其包含類型?

+0

? – MarkG 2013-05-11 14:45:37

回答

0

訪問Pocos上的屬性的示例代碼。 有單個或多個屬性的版本,你在視圖中輸出列表中使用何種方法的HtmlHelper看

樣品調用方法

var MutliAttributeList = MyStatic.GetPocoMultiAttribute<MyAttribute>(typeof(poco),"AttrName"); 


public static UAttribute GetPocoAttribute<TPoco, UAttribute>(string attributeName) { 
     var result = typeof (TPoco).GetCustomAttributes(true) 
            .Where(attribute => attribute.GetType() 
                   .Name == attributeName) 
            .Cast<UAttribute>() 
            .FirstOrDefault(); 
     return result; 
    } 

public static IEnumerable<UAttribute> GetPocoMultiAttribute<UAttribute>(Type pocoType, string attributeName) { 
     var result = pocoType.GetCustomAttributes(true) 
          .Where(attribute => attribute.GetType() 
                  .Name == attributeName).Cast<UAttribute>().ToList(); 
     return result; 
    }