Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Web.Mvc;
- namespace SingleWebPOC.Util
- {
- public static class HtmlUtil
- {
- /*
- Examples using System.TimeZoneInfo in Model
- *
- * @Html.DropDownList("TimeZones",Model.TimeZones.ToSelectListItems())
- *
- * With text
- * @Html.DropDownList("TimeZones2",Model.TimeZones.ToSelectListItems(t => t.DaylightName))
- *
- * With text and value
- * @Html.DropDownList("TimeZones3",Model.TimeZones.ToSelectListItems(t => t.DaylightName,t => t.Id))
- *
- * With text, value and selected expression
- * @Html.DropDownList("TimeZones3",Model.TimeZones.ToSelectListItems(t => t.DaylightName,t => t.Id,t=>t.DaylightName == "Central America Daylight Time"))
- */
- /// <summary>
- /// Creates an <see cref="IEnumerable<SelectListItem>"/> base on the IEnumerable<T> items
- /// </summary>
- public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> items,
- Func<T, string> textExpression = null,
- Func<T, string> valueExpression = null,
- Func<T, bool> selectedExpression = null)
- {
- foreach (T item in items)
- {
- SelectListItem li = new SelectListItem();
- if (textExpression != null)
- li.Text = textExpression(item);
- else
- li.Text = item.ToString();
- if (valueExpression != null)
- li.Value = valueExpression(item);
- if (selectedExpression != null)
- li.Selected = selectedExpression(item);
- yield return li;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment