Created
May 14, 2016 14:43
-
-
Save kevinamorim/b94e39c50c72180e81c663f6b449b6da to your computer and use it in GitHub Desktop.
Helper class to create ready to use SelectLists for ASP.NET MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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