mardi 26 juillet 2016

How can I retrieve data from DisplayAttribute of interface?

I have the following code:

public interface TestInterface
{
    [Display(Name = "Test Property")]
    int Property { get; }
}

class TestClass : TestAttribute
{
    public int Property { get; set; }
}

Note, that the property of interface is marked with DisplayAttribute. When I am trying to get the value from attribute, the following code samples does not works.

First sample: direct access to property of class.

var t = new TestClass();

var a = t.GetType().GetProperty("Property").GetCustomAttributes(true);

Second sample: cast object to interface and get access to property.

var t = (TestInterface)new TestClass();

var a = t.GetType().GetProperty("Property").GetCustomAttributes(true);

But when I am passing object as a model for mvc view and calling @Html.DisplayNameFor(x => x.Property) it returns the correct string "Test Property".

View

@model WebApplication1.Models.TestInterface
...
@Html.DisplayNameFor(x => x.Property)

renders as

Test Property

How can I achieve the same result with code on server side? And why I can not do it with simple reflection?





Aucun commentaire:

Enregistrer un commentaire