由于在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使用的更多相关文章

  1. IEnumerable<T>转换为IList<SelectListItem>

    扩展方法IEnumerable<T>转换为IList<SelectListItem> ,提供@Html.DropDownList使用   由于在MVC中经常会使用到@Html. ...

  2. 使用扩展方法将DataTable转换为List<T>

    在将DataTable转换为List<T>时,找到了网上的方案,原文链接:http://stackoverflow.com/questions/4593663/fetch-datarow- ...

  3. 工作总结 for 另类写法 循环加时间 集合合并 也是用的 static class Enumerable (IEnumerable<T>的扩展方法) (IEnumerable<T> 的 工具类) (所有集合 数组都实现IEnumerable<T>)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  4. .NET: 谈谈C#中的扩展方法

    扩展方法(Extension Methods)是C#3.0时引入的新特性,相信很多人都听过并且也都用过,最常见的是在LINQ中的使用. 不仅如此,在开发中,我们也可以创建自己扩展方法,使用它来优化类的 ...

  5. JavaScript学习总结(十四)——JavaScript编写类的扩展方法

    在​J​a​v​a​S​c​r​i​p​t​中​可以使​用​类的p​r​o​t​o​t​y​p​e属性来​扩​展​类的属​性​和​方​法,在实际开发当中,当JavaScript内置的那些类所提供的动态 ...

  6. .net 扩展方法,lamada表达式 委托

    扩展方法 (1)扩展方法是一种特殊的静态方法,它定义在一个静态类中,但可以在其他类的对象上向调用实例方法那样进行调用.因此,通过扩展方法,我们就可以在不修改一个类型的前提下对一个类型进行功能上的扩充, ...

  7. Extension Methods(扩展方法)

    在 OOPL 中,有静态方法.实例方法和虚方法,如下:   public sealed class String {      public static bool  IsNullOrEmpty(st ...

  8. 为IEnumerable<T>添加RemoveAll<IEnumerable<T>>扩展方法--高性能篇

    最近写代码,遇到一个问题,微软基于List<T>自带的方法是public bool Remove(T item);,可是有时候我们可能会用到诸如RemoveAll<IEnumerab ...

  9. IEnumerable<T>与IQueryable<T>以及.net的扩展方法

    首先看看继承关系 public abstract class DbSet : DbQuery public abstract class DbQuery : IOrderedQueryable, IQ ...

随机推荐

  1. MySQL数据查询之多表查询

    多表查询 多表联合查询 #创建部门 CREATE TABLE IF NOT EXISTS dept ( did int not null auto_increment PRIMARY KEY, dna ...

  2. 重写equals和hashCode的方法

    为什么要有 hashCode引用 我们以"HashSet 如何检查重复"为例子来说明为什么要有 hashCode: 当你把对象加入 HashSet 时,HashSet 会先计算对象 ...

  3. jenkins可选插件为空的解决方式

    我是安装的jenkins,文件名字是这个jenkins.msi,点finish安装完成,然后浏览器就自动打开了jenkins页面,输入密码后,便进入了如下页面 之后我是选择的跳过插件安装,在可选插件里 ...

  4. eclipse配置servlet错误

    可能是因为你的web.xml里的<url>映射的名字和servlet相同

  5. 关于webconfig的记录恢复本

    <?xml version="1.0"?> <!--注意: 除了手动编辑此文件以外,您还可以使用 Web 管理工具来配置应用程序的设置.可以使用 Visual S ...

  6. s11.9 sar:收集系统信息

    功能说明: 通过sar命令,可以全面地获取系统的CPU.运行队列.磁盘I/O.分页(交换区).内存.CPU中断和网络等性能数据. 语法格式 sar  option interval count sar ...

  7. python_requests随笔

    #coding=utf-8 import requests url = "http://oj.jxust.edu.cn" #如果需要持续的链接,可以使用里面的Session方法(保 ...

  8. Chapter5 生长因子、受体和癌症

    一.Src蛋白是一种蛋白激酶 可以磷酸化不同的底物,调节不同的通路 Src激酶主要磷酸化酪氨酸残基,而别的激酶主要磷酸化色氨酸.苏氨酸残基 二.EGF受体拥有酪氨酸激酶功能 胞内结构域有Src蛋白的同 ...

  9. CPP之内存分配

    new & delete expression 1. Introduction A new expression allocates and constructs an object of a ...

  10. 分享Azure DevOps技术,来微信群吧!

    现在QQ用户越来越少,基本上都转移到微信上了. 讨论问题,动不动就来一个微信群.下面这样几百人的微信群,专门讨论Azure DevOps (TFS)技术,你加入了么? 还等什么,扫描吧!