Skip to content

Instantly share code, notes, and snippets.

@kevinamorim
Created May 14, 2016 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinamorim/b94e39c50c72180e81c663f6b449b6da to your computer and use it in GitHub Desktop.
Save kevinamorim/b94e39c50c72180e81c663f6b449b6da to your computer and use it in GitHub Desktop.
Helper class to create ready to use SelectLists for ASP.NET MVC
public static class SelectListHelper
{
private const string DataValueField = "Value";
private const string DataTextField = "Text";
public static SelectList CreateSelectList<TSource>(IEnumerable<TSource> items, string dataValuePropertyName, string dataTextPropertyName)
{
if (!ArePropertiesValid(items.FirstOrDefault(), dataValuePropertyName, dataTextPropertyName))
{
throw new ArgumentException("Such property does not exist: " + dataValuePropertyName + " or " + dataTextPropertyName);
}
var finalList = GetSelectListItems(items, dataValuePropertyName, dataTextPropertyName);
return new SelectList(finalList, DataValueField, DataTextField);
}
private static bool ArePropertiesValid<TSource>(TSource testItem, string dataValuePropertyName, string dataTextPropertyName)
{
return IsPropertyValid(testItem, dataValuePropertyName) && IsPropertyValid(testItem, dataTextPropertyName);
}
private static bool IsPropertyValid<TSource>(TSource obj, string propertyName)
{
PropertyInfo property = typeof(TSource).GetProperty(propertyName);
return property != null;
}
private static IEnumerable GetSelectListItems<TSource>(IEnumerable<TSource> items, string dataValuePropertyName, string dataTextPropertyName)
{
return items.Select(m => new
{
Value = typeof(TSource).GetProperty(dataValuePropertyName).GetValue(m).ToString(),
Text = typeof(TSource).GetProperty(dataTextPropertyName).GetValue(m)
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment