Skip to content

Instantly share code, notes, and snippets.

@lloydkevin
Last active January 11, 2021 03:59
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 lloydkevin/dc5771c30f1af6b1a81c875e14e27f85 to your computer and use it in GitHub Desktop.
Save lloydkevin/dc5771c30f1af6b1a81c875e14e27f85 to your computer and use it in GitHub Desktop.
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