扩展方法IEnumerableT转换为IListSelectListItem ,提供@Html.DropDownList使用
生活随笔
收集整理的這篇文章主要介紹了
扩展方法IEnumerableT转换为IListSelectListItem ,提供@Html.DropDownList使用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
由于在MVC中經(jīng)常會(huì)使用到@Html.DropDownList方法,而該方法接收的是List<SelectListItem> 參數(shù),因此就想著寫一個(gè)擴(kuò)展方法,直接把IEnumerable轉(zhuǎn)換為List<SelectListItem>類型,這樣使用起來會(huì)比較方便
正式進(jìn)入正文。
1、首先創(chuàng)建下面實(shí)體:
//水果類public class Fruit{public string Code { get; set; }public string Name { get; set; }public string Color { get; set; }}?
2、編寫擴(kuò)展方法,把IEnumerable轉(zhuǎn)換為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>/// 擴(kuò)展方法,IEnumerable<T>轉(zhuǎn)換為IList<SelectListItem>/// </summary>/// <typeparam name="T"></typeparam>/// <param name="data">帶轉(zhuǎn)換的數(shù)據(jù)</param>/// <param name="Text"></param>/// <param name="Value"></param>/// <param name="selectValue"></param>/// <param name="NewItem">傳遞過來的SelectListItem,如請(qǐng)選擇……</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、調(diào)用方法如下:
ViewBag.Fruits = list.ToSelectListItem(it => it.Name, it => it.Color, "", new SelectListItem() { Text = "請(qǐng)選擇水果", Value = "", Selected = true });@Html.DropDownList("Fruits ",ViewBag.Fruits as IList<SelectListItem>)?
轉(zhuǎn)載于:https://www.cnblogs.com/lc-chenlong/p/3926998.html
總結(jié)
以上是生活随笔為你收集整理的扩展方法IEnumerableT转换为IListSelectListItem ,提供@Html.DropDownList使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php二维数组的取值与转换
- 下一篇: C++ STL中哈希表 hash_map