1. 程式人生 > 實用技巧 >03.django之檢視函式

03.django之檢視函式

一、Contrl與View資料傳遞(多表資料)

1)ViewBag變數方式

使用4個ViewBag變數進行資料傳遞,Data1、Data2、Data3、Data4的資料直接從資料庫裡調。

Control中虛擬碼如下所示:

public ActionResult CnBlogIndex()
2         {
3             ViewBag.Data1 = Data1;
4             ViewBag.Data2 = Data2;
5             ViewBag.Data3 = Data3;
6             ViewBag.Data4 = Data4;
7 return View(); 8 }

View中虛擬碼如下所示:

//第一塊內容
 2 @foreach (Data1 data in (ViewBag.Data1 as IEnumerable<Data1>))
 3 {
 4     <tr>
 5         <td>@Html.DisplayFor(model => data.ID)</td>
 6     </tr>
 7 }
 8 //第二塊內容
 9 @foreach (Data2 dat1 in (ViewBag.Data2 as IEnumerable<Data2>))
10 { 11 <tr> 12 <td>@Html.DisplayFor(model => data.ID)</td> 13 </tr> 14 } 15 //第三塊內容 16 @foreach (Data3 data in (ViewBag.Data3 as IEnumerable<Data3>)) 17 { 18 <tr> 19 <td>@Html.DisplayFor(model => data.ID)</td> 20 </tr> 21 }
22 //第四塊內容 23 @foreach (Data4 data in (ViewBag.Data4 as IEnumerable<Data4>)) 24 { 25 <tr> 26 <td>@Html.DisplayFor(model => data.ID)</td> 27 </tr> 28 }

2)ViewModel方式(推薦)

什麼是ViewModel?ViewModel就是針對檢視做的Model,讓Model更加適合於View。Data1、Data2、Data3、Data4的資料直接從資料庫裡取出,然後組裝給ViewModel,ViewModel做為整個頁面的資料載體進行資料傳遞:

ViewModel中的虛擬碼如下所示:

public class CnBlogIndex {
2         List<Data> Data1 { get; set; }
3         List<Data> Data2 { get; set; }
4         List<Data> Data3 { get; set; }
5         List<Data> Data4 { get; set; }
6     }

Control中虛擬碼如下所示:

  public ActionResult CnBlogIndex()
         {
             ViewModel.CnBlogIndex CnBlogIndex = new ViewModel.CnBlogIndex();
             CnBlogIndex.Data1 = Data1;
             CnBlogIndex.Data2 = Data2;
             CnBlogIndex.Data3 = Data3;
             CnBlogIndex.Data4 = Data4;
             return View(CnBlogIndex);
         }

View中虛擬碼如下所示:

@model CnBlogIndex
 2 @foreach (var info in Model.Data1)
 3     {
 4         <tr>
 5             <td>info.**</td>
 6         </tr>
 7     }
 8 @foreach (var info in Model.Data2)
 9     {
10         <tr>
11             <td>info.**</td>
12         </tr>
13     }
14 @foreach (var info in Model.Data3)
15     {
16         <tr>
17             <td>info.**</td>
18         </tr>
19     }
20 @foreach (var info in Model.Data4)
21     {
22         <tr>
23             <td>info.**</td>
24         </tr>
25     }