using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace GreenTree.Strohrmann.ERP.Web.Extension { public static class ViewDataExtension { /// /// Adds a predefined selection item list in the ViewData dictionary used by many HtmlContent input methods /// /// The list base value type. /// The ViewData dictionary. /// The ViewData key. /// The base data source. /// The expression for the value. /// The expression for the display text. /// The value of the optional pre selected item. public static void AddSelectList(this ViewDataDictionary viewDataDict, string key, IEnumerable source, Func valueExpression, Func textExpression, object selectedValue = null) { if (viewDataDict == null) return; if (String.IsNullOrEmpty(key)) return; if (source == null) throw new ArgumentNullException("source", "The specified data source must not be NULL."); var selectItemList = new List(); foreach (var item in source) { var val = valueExpression(item).ToString(); var text = textExpression(item).ToString(); if (selectedValue != null && val == selectedValue.ToString()) selectItemList.Add(new SelectListItem(text, val, true)); else selectItemList.Add(new SelectListItem(text, val)); } viewDataDict.Add(key, selectItemList); } } }