MVC匿名類傳值學習

來源:互聯網
上載者:User

標籤:元組   var   display   功能   strong   string   nbsp   closed   elements   

  剛接觸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 12Console.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匿名類傳值學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.