I don't know much details of GetSelectList
method there, but I assumed it receives a System.Enum
and returning a SelectList
collection like this:
public static SelectList GetSelectList(this Enum enumeration)
{
var source = Enum.GetValues(enumeration);
// other stuff
...
return new SelectList(...);
}
There are 2 approaches to solve this issue:
First Approach (Using Custom Attribute)
This approach involves creating a custom attribute to define display name (set attribute target to field or others which fit to entire enum members):
public class DisplayNameAttribute : Attribute
{
public string DisplayName { get; protected set; }
public DisplayNameAttribute(string value)
{
this.DisplayName = value;
}
public string GetName()
{
return this.DisplayName;
}
}
Hence, the enum structure should be modified to this:
public enum QuestionType
{
[DisplayName("Single Choice")]
Single_Choice,
[DisplayName("Multiple Choice")]
Multiple_Choice,
[DisplayName("By Range")]
Range
}
Later, it is necessary to modify GetSelectList
method to accept custom attribute created above which includes DisplayName
property:
public static SelectList GetSelectList<T>(this T enumeration)
{
var source = Enum.GetValues(typeof(T));
var items = new Dictionary<Object, String>();
var displaytype = typeof(DisplayNameAttribute);
foreach (var value in source)
{
System.Reflection.FieldInfo field = value.GetType().GetField(value.ToString());
DisplayNameAttribute attr = (DisplayNameAttribute)field.GetCustomAttributes(displaytype, false).FirstOrDefault();
items.Add(value, attr != null ? attr.GetName() : value.ToString());
}
return new SelectList(items, "Key", "Value");
}
Second Approach (Using Direct Type Cast & Lambda)
Similar to first approach, GetSelectList
method will return SelectList
from an enum
, however instead of using custom attribute this approach uses member names to build select list items as shown below (T
is enum type parameter):
public static SelectList GetSelectList<T>(this T enumeration)
{
var source = Enum.GetValues(typeof(T)).Cast<T>().Select(x => new SelectListItem() {
Text = x.ToString(),
Value = x.ToString().Replace("_", " ")
});
return new SelectList(source);
}
Probably GetSelectList
method contents in your side is slightly different, but the basics should be same with those approaches.
Similar issues:
How do I populate a dropdownlist with enum values?
Display enum in ComboBox with spaces
enum with space property for dropdownlist