最近在开发mvc3的时候发现了一个问题,就是如何在view页面显示多表查询的数据,最简单的办法就是使用viewmodel了,以下本人使用viewmodel来实现多表查询的3中方法,
先贴代码再说:
1 第一种是将页面显示多表的数据(也就是汇总各个model表的字段),然后再viewmodel中显示
1 public class ResultAdList 2 { 3 public int A_Id; 4 public string A_userid; 5 public int B_Id; 6 public string B_typename; 7 }
public class AdRepository { private DataAdDataContext db = new DataAdDataContext(); public IQueryable<ResultAdList> AdList { get; private set; } public AdRepository() { this.AdList = from a in db.R_ad_list join b in db.R_ad_type on a.A_typeid equals b.id select new ResultAdList { A_Id = a.id, A_userid = a.A_userid, B_Id = b.id, B_typename=b.T_ad_typename }; } }
1 public ActionResult Index() 2 { 3 return View("Index", new AdRepository()); 4 }
view中这样写:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Dmj.Models.AdRepository>" %> <% foreach (var item in Model.AdList) { %> <% } %>
接着第二中方法:
1 public class demoshopViewModels 2 3 { 4 5 public IEnumerable<商店> shop { get; set; } 6 7 public IEnumerable<演示> demo { get; set; } 8 9 }
linq方法可参照AdRepository方法,大同小异,路过
view中这样写
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication.ViewModels.demoshopViewModels>" %> <%foreach (var item in Model.shop) { //這裡是shop Models } %> <%foreach (var item in Model.demo) { //這裡是demo Models } %>
第三种直接上图:
model中
viewmodel图
view图
目测三种方法都差不多,只有细微的差别,个人觉得第三中最简单也是最常用的