由于在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. 事件委托在ios下面失效

    $(document).on("click","目标class",function(){ //安卓下点击可以,ios下面失效 }) 百度了下说是H5新定义的, ...

  2. 密码\路径\IP...备忘录

    1.linux 192.168.200.128:22 root/123456

  3. Sort Array By Parity II LT922

    Given an array A of non-negative integers, half of the integers in A are odd, and half of the intege ...

  4. 简单利用jQuery,让前端开发不再依赖于后端的接口

    前端开发的过程中,我们免不了和后端进行联调,这时候就会出现以下的尴尬场景: 接口没写好,没法做接下来的功能 功能写好了,接口没写好,没法测这个功能 联调了,出了BUG,不知道锅在谁身上,只得陪后端耗时 ...

  5. Python Day 14 迭代器、for循环原理、枚举、生成器

    阅读内容 内容回顾   带参装饰器和wraps用法   迭代器知识引入   可迭代对象   迭代器对象   for循环迭代器   枚举对象   生成器 ##内容回顾 函数的嵌套定义:在函数内部定义另一 ...

  6. Python基础整理

    第一章 Python介绍 1.3 基本类型 操作符 +,-,*,/,%,**(幂),divmod(除法) divmod(10,3)=(3,1) None表示出错 表示假: None,0,0.0,&qu ...

  7. 20155339 Exp9 Web安全基础

    Exp9 Web安全基础 基础问题回答 (1)SQL注入攻击原理,如何防御 原理:它是利用现有应用程序,将恶意的SQL命令注入到后台数据库引擎执行的能力,它可以通过在Web表单中输入恶意SQL语句得到 ...

  8. js-实时获取键值码

    <script> document.onkeydown=function(event){ console.log(event.keyCode)    //在控制台打印 } </scr ...

  9. [算法专题] 二分搜索&排序数组

    基础知识 二分非递归写法: int binary_search(const int a[], const int size, const int val) { int lower = 0; int u ...

  10. 【转】学习Java虚拟机没用? 听听当事人是怎么说的!

    我是大名鼎鼎的Java 虚拟机,  据说这个星球上每天有900多万程序员和我打交道,这真是一个惊人的数字. 这900多万人中不少人对我的技术内幕非常感兴趣, 有事儿没事儿都要把我“大卸八块”, 深入了 ...