| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- 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
- {
- /// <summary>
- /// Adds a predefined selection item list in the ViewData dictionary used by many HtmlContent input methods
- /// </summary>
- /// <typeparam name="TValue">The list base value type.</typeparam>
- /// <param name="viewDataDict">The ViewData dictionary.</param>
- /// <param name="key">The ViewData key.</param>
- /// <param name="source">The base data source.</param>
- /// <param name="valueExpression">The expression for the value.</param>
- /// <param name="textExpression">The expression for the display text.</param>
- /// <param name="selectedValue">The value of the optional pre selected item.</param>
- public static void AddSelectList<TValue>(this ViewDataDictionary viewDataDict,
- string key, IEnumerable<TValue> source, Func<TValue, object> valueExpression, Func<TValue, object> 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<SelectListItem>();
- 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);
- }
- }
- }
|