您的位置:首页 > 编程语言 > ASP

一段用于生成 ASP.NET MVC 中 DropDownListFor 的 SelectListItem 可枚举的集合

2013-02-06 15:08 411 查看
直接贴代码了:

public static class EnumerableExtension
{
/// <summary>
/// 生成用于 ASP.NET Mvc 中 DropDownListFor 的 SelectListItem 可枚举的集合
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="source">集合</param>
/// <param name="funText">得到下拉框的 Text 的委托</param>
/// <param name="funValue">得到下拉框的 Value 的委托</param>
/// <param name="selectedValue">选中的值。建议不要设置与模型状态不一致的值,比如当前提交的下拉框中的值为 1,您如果设置 2,那么还是会显示 1,因为 Mvc 默认会从当前上下文中取值</param>
/// <param name="initItems">初始化项,可为 null</param>
/// <returns></returns>
public static IEnumerable<SelectListItem> ToDropDownListItems<T>(this IEnumerable<T> source, Func<T, string> funText, Func<T, string> funValue, string selectedValue, IDictionary<string, string> initItems = null)
{
if (initItems != null && initItems.Count > 0)
{
foreach (var item in initItems)
{
SelectListItem resultItem = new SelectListItem
{
Text = item.Key,
Value = item.Value,
Selected = item.Value == selectedValue
};
yield return resultItem;
}
}
if (source != null)
{
IEnumerator<T> sourceIterator = source.GetEnumerator();
while (sourceIterator.MoveNext())
{
T entityItem = sourceIterator.Current;
yield return new SelectListItem
{
Text = funText(entityItem),
Value = funValue(entityItem),
Selected = funValue(entityItem) == selectedValue
};
}
}
}
}


简单调用:

ViewBag.dropDownListForNewsType = list.ToDropDownListItems(m => m.Name, m => m.Id.ToString(), viewModel.NewsType.ToString());


复杂调用:

ViewBag.dropDownListForParentId = listCategories.ToDropDownListItems(
m => m.DepthLevel <= 1 ? (m.Name) : ("|" + new string('-', m.DepthLevel * m.DepthLevel) + m.Name),
m => m.Id.ToString(),
viewModel.ParentId.ToString(),
new Dictionary<string, string>() { { "===请选择===", "0" } }
);


运行效果图:

简单调用的运行效果图:



复杂调用的运行效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: