You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.0 KiB

10 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Web.Mvc;
  5. namespace Sevomin.Models.Helpers
  6. {
  7. public class StringValue : System.Attribute
  8. {
  9. private string _value;
  10. public StringValue(string value)
  11. {
  12. _value = value;
  13. }
  14. public string Value
  15. {
  16. get { return _value; }
  17. }
  18. }
  19. public static class StringEnum
  20. {
  21. public static SelectList GetSelectList(Type inputEnum, bool textAsValue)
  22. {
  23. List<SelectListItem> retList = new List<SelectListItem>();
  24. if (inputEnum.IsEnum)
  25. {
  26. foreach (Enum property in Enum.GetValues(inputEnum))
  27. {
  28. retList.Add(new SelectListItem
  29. {
  30. Text = GetStringValue(property),
  31. Value = Convert.ToInt16(inputEnum.GetField(property.ToString()).GetValue(null)).ToString() //textAsValue ? GetStringValue(property) : property.ToString()
  32. });
  33. }
  34. return new SelectList(retList, "Value", "Text");
  35. }
  36. else
  37. throw new InvalidOperationException("The input type is not an enum.");
  38. }
  39. public static string GetStringValue(Enum value)
  40. {
  41. Type type = value.GetType();
  42. //Check first in our cached results...
  43. //Look for our 'StringValueAttribute'
  44. //in the field's custom attributes
  45. FieldInfo fi = type.GetField(value.ToString());
  46. StringValue[] attrs =
  47. fi.GetCustomAttributes(typeof(StringValue),
  48. true) as StringValue[];
  49. foreach (var item in attrs)
  50. {
  51. if (!string.IsNullOrEmpty(item.Value))
  52. return item.Value;
  53. }
  54. return string.Empty;
  55. }
  56. }
  57. }