一、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 }