andrew4582

ToSelectListItems MVC Html Utility

Oct 5th, 2013
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web.Mvc;
  4.  
  5. namespace SingleWebPOC.Util
  6. {
  7.     public static class HtmlUtil
  8.     {
  9.         /*
  10.          Examples using System.TimeZoneInfo in Model
  11.          *
  12.          * @Html.DropDownList("TimeZones",Model.TimeZones.ToSelectListItems())
  13.          *
  14.          * With text
  15.          * @Html.DropDownList("TimeZones2",Model.TimeZones.ToSelectListItems(t => t.DaylightName))
  16.          *
  17.          * With text and value
  18.          * @Html.DropDownList("TimeZones3",Model.TimeZones.ToSelectListItems(t => t.DaylightName,t => t.Id))
  19.          *
  20.          * With text, value and selected expression
  21.          * @Html.DropDownList("TimeZones3",Model.TimeZones.ToSelectListItems(t => t.DaylightName,t => t.Id,t=>t.DaylightName == "Central America Daylight Time"))
  22.          */
  23.  
  24.         /// <summary>
  25.         /// Creates an <see cref="IEnumerable<SelectListItem>"/> base on the IEnumerable<T> items
  26.         /// </summary>
  27.         public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> items,
  28.             Func<T, string> textExpression = null,
  29.             Func<T, string> valueExpression = null,
  30.             Func<T, bool> selectedExpression = null)
  31.         {
  32.             foreach (T item in items)
  33.             {
  34.                 SelectListItem li = new SelectListItem();
  35.                 if (textExpression != null)
  36.                     li.Text = textExpression(item);
  37.                 else
  38.                     li.Text = item.ToString();
  39.  
  40.                 if (valueExpression != null)
  41.                     li.Value = valueExpression(item);
  42.  
  43.                 if (selectedExpression != null)
  44.                     li.Selected = selectedExpression(item);
  45.  
  46.                 yield return li;
  47.             }
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment