Last active
January 11, 2021 03:59
-
-
Save lloydkevin/dc5771c30f1af6b1a81c875e14e27f85 to your computer and use it in GitHub Desktop.
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
using Microsoft.AspNetCore.Mvc.Rendering; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace JetStreamCore.Web.Pages | |
{ | |
public static class SelectListItemExtensions | |
{ | |
/// <summary> | |
/// https://codereview.stackexchange.com/questions/101061/helper-for-dropdownlists-with-extension-method | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="source"></param> | |
/// <param name="value">Value function</param> | |
/// <param name="text">Text function</param> | |
/// <param name="selected">Selected condition</param> | |
/// <returns></returns> | |
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> source, Func<T, string> value, Func<T, string> text, Func<T, bool> selected = null) | |
{ | |
return source.Select(x => new SelectListItem | |
{ | |
Value = value(x) ?? "", | |
Text = text(x), | |
Selected = selected != null ? selected(x) : false | |
}); | |
} | |
public static SelectList ToSelectList(this IEnumerable items, string dataValueField = "Value", string dataTextField = "Text") | |
{ | |
return new SelectList(items, dataValueField, dataTextField); | |
} | |
public static SelectList ToSelectList(this IEnumerable items, string dataValueField, string dataTextField, object selectedValue) | |
{ | |
return new SelectList(items, dataValueField, dataTextField, selectedValue); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment