jpo
jpo

Reputation: 4059

MVC: Access display name attribute in the controller

Is it possible to access the display name of a parameter in the controller? for example, say I defined a parameter as

public class Class1
{
  [DisplayName("First Name")]
  public string firstname { get; set; }
}

I now want to be able to access the display name of firstname in my controller. Something like

string name = Model.Class1.firstName.getDisplayName();

Is there a method like getDisplayName() that I can use to get the display name?

Upvotes: 4

Views: 10580

Answers (3)

LateshtClick.com
LateshtClick.com

Reputation: 616

Display name for Enum is like this

Here is example

public enum Technology
{
  [Display(Name = "AspNet Technology")]
  AspNet,
  [Display(Name = "Java Technology")]
  Java,
  [Display(Name = "PHP Technology")]
  PHP,
}

and method like this

public static string GetDisplayName(this Enum value)
{
var type = value.GetType();

var members = type.GetMember(value.ToString());
if (members.Length == 0) throw new ArgumentException(String.Format("error '{0}' not found in type '{1}'", value, type.Name));

var member = members[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value));

var attribute = (DisplayAttribute)attributes[0];
return attribute.GetName();
}

And your controller like this

public ActionResult Index()
{
  string DisplayName = Technology.AspNet.GetDisplayName();

  return View();
}

for class property follow this step

public static string GetDisplayName2<TSource, TProperty> (Expression<Func<TSource, TProperty>> expression)
    {
        var attribute =   Attribute.GetCustomAttribute(((MemberExpression)expression.Body).Member, typeof(DisplayAttribute)) as DisplayAttribute;
        return attribute.GetName();
    }

and call this method in your controller like this

// Class1 is your classname and firstname is your property of class
string localizedName = Testing.GetDisplayName2<Class1, string>(i => i.firstname);

Upvotes: 1

jitender sharma
jitender sharma

Reputation: 191

First off, you need to get a MemberInfo object that represents that property. You will need to do some form of reflection:

MemberInfo property = typeof(Class1).GetProperty("Name");

(I'm using "old-style" reflection, but you can also use an expression tree if you have access to the type at compile-time)

Then you can fetch the attribute and obtain the value of the DisplayName property:

var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName;

Upvotes: 7

jpo
jpo

Reputation: 4059

Found the answer at this link. I created an Html helper class, added its namespace to my view web.config and used it in my controller. All described in the link

Upvotes: 1

Related Questions