Membangun jawaban Thomas Stock, saya menciptakan ToSelectList
metode kelebihan ini :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
public static partial class Helpers
{
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, bool selectAll = false)
{
return enumerable.ToSelectList(value, value, selectAll);
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, object selectedValue)
{
return enumerable.ToSelectList(value, value, new List<object>() { selectedValue });
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, IEnumerable<object> selectedValues)
{
return enumerable.ToSelectList(value, value, selectedValues);
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, bool selectAll = false)
{
foreach (var f in enumerable.Where(x => x != null))
{
yield return new SelectListItem()
{
Value = value(f).ToString(),
Text = text(f).ToString(),
Selected = selectAll
};
}
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, object selectedValue)
{
return enumerable.ToSelectList(value, text, new List<object>() { selectedValue });
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, IEnumerable<object> selectedValues)
{
var sel = selectedValues != null
? selectedValues.Where(x => x != null).ToList().ConvertAll<string>(x => x.ToString())
: new List<string>();
foreach (var f in enumerable.Where(x => x != null))
{
yield return new SelectListItem()
{
Value = value(f).ToString(),
Text = text(f).ToString(),
Selected = sel.Contains(value(f).ToString())
};
}
}
}
Di controller Anda, Anda dapat melakukan hal berikut:
var pageOptions = new[] { "10", "15", "25", "50", "100", "1000" };
ViewBag.PageOptions = pageOptions.ToSelectList(o => o, "15" /*selectedValue*/);
Dan akhirnya di View Anda, masukkan:
@Html.DropDownList("PageOptionsDropDown", ViewBag.PageOptions as IEnumerable<SelectListItem>, "(Select one)")
Ini akan menghasilkan output yang diinginkan - tentu saja, Anda dapat meninggalkan "(Select one)"
optionLabel di atas jika Anda tidak ingin item kosong pertama:
<select id="PageOptionsDropDown" name="PageOptionsDropDown">
<option value="">(Select one)</option>
<option value="10">10</option>
<option selected="selected" value="15">15</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="1000">1000</option>
</select>
Pembaruan: Daftar kode yang direvisi dapat ditemukan di sini dengan komentar XML.