首页 > Web开发 > 详细

MVC匿名类传值学习

时间:2017-07-16 13:19:15      阅读:248      评论:0      收藏:0      [点我收藏+]

  刚接触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方法

 

MVC匿名类传值学习

原文:http://www.cnblogs.com/fuxuyang/p/7190090.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!