Ottieni l'attributo DisplayAttribute da PropertyInfo
-
27-10-2019 - |
Domanda
class SomeModel
{
[Display(Name = "Quantity Required")]
public int Qty { get; set; }
[Display(Name = "Cost per Item")]
public int Cost { get; set; }
}
Sto cercando di mappare il modello in un elenco di { PropertyName, DisplayName }
coppie, ma sono rimasto bloccato.
var properties
= typeof(SomeModel)
.GetProperties()
.Select(p => new
{
p.Name,
p.GetCustomAttributes(typeof(DisplayAttribute),
false).Single().ToString()
}
);
Quanto sopra non si compila e non sono sicuro che sia comunque l'approccio giusto, ma spero che tu possa vedere l'intento. Qualche puntatore? Grazie
Soluzione
È necessario definire diversi nomi di proprietà per il tipo anonimo.
var properties = typeof(SomeModel).GetProperties()
.Where(p => p.IsDefined(typeof(DisplayAttribute), false))
.Select(p => new
{
PropertyName = p.Name, p.GetCustomAttributes(typeof(DisplayAttribute),
false).Cast<DisplayAttribute>().Single().Name
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow