MVC匿名类传值学习

  刚接触MVC+EF框架不久,但一直很困惑的就是控制器能否及如何向视图传递匿名类数据。宝宝表示很讨厌去新建实体类啦,查询稍有不同就去建一个实体类不是很麻烦吗,故趁阳光正好,周末睡到自然醒后起来尝试了之前一直在博客园看到的实现方式:英明神武的Tuple类,第一次对微软钦佩之至。故做如下记录,方便自己之后使用。大神就勿喷我啦,宝宝第一次写博客。

  首先先描述一下我要实现的功能:从控制器后台查询一些数据,通过匿名类存储,在视图前端遍历输出。初衷实现流程如下:

控制器部分:

      private repairsystemEntities db = new repairsystemEntities();
        // GET: TEST
        public ActionResult Index()
        {
            var Info = db.bom.ToList().Select(p => Tuple.Create(p.Bom_Brand, p.Bom_Model));
            ViewBag.Info = Info;
            return View();
        } 

视图部分:

<table class="table table-hover">
    <tbody>
    @foreach(var item in ViewBag.Info)
    {
        <tr>
            <td>@(item.Item1)</td>
        </tr>
    }
    </tbody>
</table>

附Tuple类简单说明如下,全部来源于微软官方文档,地址

语法

public static Tuple<T1> Create<T1>(
	T1 item1
) 
  参数

  item1

  Type: T1

  元组仅有的分量的值。

  返回值

  Type: System.Tuple<T1>

  元组,其值为 (item1)

使用方法

//类构造函数
var tuple1 = new Tuple<int>(12);
//helper方法
var tuple2 = Tuple.Create(12);
//获取值方法直接采用
Console.WriteLine(tuple1.Item1);     // Displays 12
Console.WriteLine(tuple2.Item1);     // Displays 12

实际例子

// Create a 7-tuple.
var population = new Tuple<string, int, int, int, int, int, int>(
                           "New York", 7891957, 7781984, 
                           7894862, 7071639, 7322564, 8008278);
// Display the first and last elements.
Console.WriteLine("Population of {0} in 2000: {1:N0}",
                  population.Item1, population.Item7);
// The example displays the following output:
//       Population of New York in 2000: 8,008,278
类构造函数创建
// Create a 7-tuple.
var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278);
// Display the first and last elements.
Console.WriteLine("Population of {0} in 2000: {1:N0}",
                  population.Item1, population.Item7);
// The example displays the following output:
//       Population of New York in 2000: 8,008,278
Create方法

 

转载于:https://www.cnblogs.com/fuxuyang/p/7190090.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值