user777310
user777310

Reputation: 215

MVC EnumMember custom string

I had this set of Enums for currency purpose

[DataContract]
public enum PaymentCurrency
{

    /// <summary>
    /// Canadian dollar.
    /// </summary>
    [EnumMember(Value = "CA$")]
    CAD = 1,
}

When I want to display the particular item , for example CAD , I want it to show as "CA$" string . I tried it by assigning a value to it , it is not working and I haven't got much clue . Any ideas ? Thanks .

Upvotes: 2

Views: 2387

Answers (1)

Paul Oliver
Paul Oliver

Reputation: 7671

The value argument of the EnumMember attribute is there for serialization. Not display purposes. See MSDN Documentation.

To get at that value you'd have to serialize it then parse the XML.

Another way is to write your own helper method and take advantage of C# built-in DescriptionAttribute:

public enum PaymentCurrency
{
  [DescriptionAttribute("CA$")]
  CAD,
  [DescriptionAttribute("US$")]
  USD,
  EURO
}

Then using your own helper methods in an EnumUtils class you could do this:

public class EnumUtils
{
  public static string stringValueOf(Enum value)
  {
    var fi = value.GetType().GetField(value.ToString());
    var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof(DescriptionAttribute), false);
    if (attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return value.ToString();
    }
  }

  public static object enumValueOf(string value, Type enumType)
  {
    string[] names = Enum.GetNames(enumType);
    foreach (string name in names)
    {
      if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
      {
          return Enum.Parse(enumType, name);
      }
    }

    throw new ArgumentException("The string is not a description or value of the specified enum.");
  }
}

Upvotes: 2

Related Questions