ViewDataExtension.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using Microsoft.AspNetCore.Mvc.Rendering;
  2. using Microsoft.AspNetCore.Mvc.ViewFeatures;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Threading.Tasks;
  8. namespace GreenTree.Strohrmann.ERP.Web.Extension
  9. {
  10. public static class ViewDataExtension
  11. {
  12. /// <summary>
  13. /// Adds a predefined selection item list in the ViewData dictionary used by many HtmlContent input methods
  14. /// </summary>
  15. /// <typeparam name="TValue">The list base value type.</typeparam>
  16. /// <param name="viewDataDict">The ViewData dictionary.</param>
  17. /// <param name="key">The ViewData key.</param>
  18. /// <param name="source">The base data source.</param>
  19. /// <param name="valueExpression">The expression for the value.</param>
  20. /// <param name="textExpression">The expression for the display text.</param>
  21. /// <param name="selectedValue">The value of the optional pre selected item.</param>
  22. public static void AddSelectList<TValue>(this ViewDataDictionary viewDataDict,
  23. string key, IEnumerable<TValue> source, Func<TValue, object> valueExpression, Func<TValue, object> textExpression,
  24. object selectedValue = null)
  25. {
  26. if (viewDataDict == null) return;
  27. if (String.IsNullOrEmpty(key)) return;
  28. if (source == null)
  29. throw new ArgumentNullException("source", "The specified data source must not be NULL.");
  30. var selectItemList = new List<SelectListItem>();
  31. foreach (var item in source)
  32. {
  33. var val = valueExpression(item).ToString();
  34. var text = textExpression(item).ToString();
  35. if (selectedValue != null && val == selectedValue.ToString())
  36. selectItemList.Add(new SelectListItem(text, val, true));
  37. else
  38. selectItemList.Add(new SelectListItem(text, val));
  39. }
  40. viewDataDict.Add(key, selectItemList);
  41. }
  42. }
  43. }