由于在MVC中经常会使用到@Html.DropDownList方法,而该方法接收的是List<SelectListItem> 参数,因此就想着写一个扩展方法,直接把IEnumerable转换为List<SelectListItem>类型,这样使用起来会比较方便
正式进入正文。
1、首先创建下面实体:
//水果类 public class Fruit { public string Code { get; set; } public string Name { get; set; } public string Color { get; set; } }
2、编写扩展方法,把IEnumerable转换为List<SelectListItem>类型,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Common { public static class Extensions { /// <summary> /// 扩展方法,IEnumerable<T>转换为IList<SelectListItem> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data">带转换的数据</param> /// <param name="Text"></param> /// <param name="Value"></param> /// <param name="selectValue"></param> /// <param name="NewItem">传递过来的SelectListItem,如请选择……</param> /// <returns></returns> public static IList<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> data, Expression<Func<T, object>> Text, Expression<Func<T, object>> Value, string selectValue = "",SelectListItem NewItem=null) where T : class,new() { var list = new List<SelectListItem>(); if (NewItem != null) { list.Add(NewItem); } string _text = ""; string _value = ""; if (Text.Body is MemberExpression) { MemberExpression TextMember = (MemberExpression)Text.Body; _text = TextMember.Member.Name; } else if (Text.Body is UnaryExpression) { UnaryExpression TextMember = (UnaryExpression)Value.Body; _text = (TextMember.Operand as MemberExpression).Member.Name; } if (Value.Body is MemberExpression) { MemberExpression ValueMember = (MemberExpression)Text.Body; _value = ValueMember.Member.Name; } else if (Value.Body is UnaryExpression) { UnaryExpression ValueMember = (UnaryExpression)Value.Body; _value = (ValueMember.Operand as MemberExpression).Member.Name; } var type = new T().GetType(); var TextPropertyInfo = type.GetProperty(_text); var ValuePropertyInfo = type.GetProperty(_value); foreach (var item in data) { var selectItem = new SelectListItem() { Text = TextPropertyInfo.GetValue(item).ToString(), Value = ValuePropertyInfo.GetValue(item).ToString() }; if (!string.IsNullOrWhiteSpace(selectValue) && selectValue == selectItem.Value) { selectItem.Selected = true; } list.Add(selectItem); } return list; } }
3、调用方法如下:
ViewBag.Fruits = list.ToSelectListItem(it => it.Name, it => it.Color, "", new SelectListItem() { Text = "请选择水果", Value = "", Selected = true }); @Html.DropDownList("Fruits ",ViewBag.Fruits as IList<SelectListItem>)
扩展方法IEnumerable<T>转换为IList<SelectListItem> ,提供@Html.DropDownList使用
时间: 2024-11-04 12:14:19