Skip to content

Instantly share code, notes, and snippets.

@yicone
Created December 13, 2012 10:46
Show Gist options
  • Select an option

  • Save yicone/4275665 to your computer and use it in GitHub Desktop.

Select an option

Save yicone/4275665 to your computer and use it in GitHub Desktop.
ASP.NET MVC
public class SelectListFactory
{
public static IEnumerable<SelectListItem> Create<TEnum, T>(bool addAll)
where TEnum : struct
where T : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("Enum is required.", "TEnum");
if (typeof(T) != Enum.GetUnderlyingType(typeof(TEnum))) throw new ArgumentException("Enum's underlying type is required", "T");
var collection = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
return Create<TEnum, T>(collection, addAll);
}
public static IEnumerable<SelectListItem> Create<TEnum, T>(IEnumerable<TEnum> collection, bool addAll)
where TEnum : struct
where T : struct
{
// http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc
if (!typeof(TEnum).IsEnum) throw new ArgumentException("Enum is required.", "TEnum");
if (typeof(T) != Enum.GetUnderlyingType(typeof(TEnum))) throw new ArgumentException("Enum's underlying type is required", "T");
var values = from TEnum e in collection
select new
{
Id = (T)Convert.ChangeType(e, typeof(T), CultureInfo.InvariantCulture),
Name = e.ToString()
};
return Create<object>(values, "Id", "Name", addAll);
}
public static IEnumerable<SelectListItem> Create<T>(IEnumerable<T> collection, string dataValueField, string dataTextField)
{
return Create<T>(collection, dataValueField, dataTextField, false);
}
public static IEnumerable<SelectListItem> Create<T>(IEnumerable<T> collection, string dataValueField, string dataTextField, bool addAll)
{
List<SelectListItem> sliList = new SelectList(collection, dataValueField, dataTextField).ToList();
if (addAll)
{
sliList.Insert(0, new SelectListItem { Text = "全部", Value = "" });
}
return sliList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment