1. 程式人生 > 實用技巧 >ViewData對於從後臺傳list到前臺的使用

ViewData對於從後臺傳list到前臺的使用

一、目標

在C# MVC開發模式下了解ViewData怎麼講一個List<Model>傳到前臺,並且前臺怎麼迴圈讀取出資料

二、平臺

vs2019, MVC模式

三、重要部分控制器程式碼展示

 #region 5.PC詳情頁
        public ActionResult PcDetail()
        {
            string pcUID = Request["id"].Trim();
            if (pcUID!=null || pcUID !="")
            {
                //PC詳情資料
                PcBLL pcbll = new
PcBLL(); PcModel pm = new PcModel(); pm = pcbll.getPcByUID(pcUID); //PC配件<CPU>資料 List<PcPart> pp = new List<PcPart>(); pp= pcbll.getPcPartByPcID_class(pcUID); ViewData["pcPart"] = pp;
return View(pm); } return Content("沒有這樣的資料"); } #endregion

四、前端檢視寫法

@{
                    var pcParts = ViewData["pcPart"] as List<PcPart>;
                    if (pcParts != null && pcParts.Any())
                    {
                        foreach
(var item in pcParts) { <tr> <td>@item.pcPartClass</td> <td>@item.brand</td> <td>@item.xModel</td> <td>@item.specification</td> <td>@item.price</td> <td>@item.repairStart</td> <td>@item.repairEnd</td> <td>@item.editTime</td> <td>@item.createTime</td> <td>@item.Note</td> </tr> } } }

五、程式碼解析:

檢視中先引用@using 引用實體類(僅引用實體類即可,無需引用具體物件名)

檢視中html要展示資料區域寫上@{},然後將控制檯定義的ViewData轉換成List<Model>以便迴圈。

如例子中:var pcParts = ViewData["pcPart"] as List<PcPart>; 就是將接收到的viewdata轉換成一個listModel,便於我們用foreach迴圈。

摘抄自:https://blog.csdn.net/xoofly/article/details/94454952