標籤:元組 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,278Create方法
MVC匿名類傳值學習