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

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
namespace Sevomin.Models.Helpers
{
public class StringValue : System.Attribute
{
private string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
public static class StringEnum
{
public static SelectList GetSelectList(Type inputEnum, bool textAsValue)
{
List<SelectListItem> retList = new List<SelectListItem>();
if (inputEnum.IsEnum)
{
foreach (Enum property in Enum.GetValues(inputEnum))
{
retList.Add(new SelectListItem
{
Text = GetStringValue(property),
Value = Convert.ToInt16(inputEnum.GetField(property.ToString()).GetValue(null)).ToString() //textAsValue ? GetStringValue(property) : property.ToString()
});
}
return new SelectList(retList, "Value", "Text");
}
else
throw new InvalidOperationException("The input type is not an enum.");
}
public static string GetStringValue(Enum value)
{
Type type = value.GetType();
//Check first in our cached results...
//Look for our 'StringValueAttribute'
//in the field's custom attributes
FieldInfo fi = type.GetField(value.ToString());
StringValue[] attrs =
fi.GetCustomAttributes(typeof(StringValue),
true) as StringValue[];
foreach (var item in attrs)
{
if (!string.IsNullOrEmpty(item.Value))
return item.Value;
}
return string.Empty;
}
}
}