最近在开发mvc3的时候发现了一个问题,就是如何在view页面显示多表查询的数据,最简单的办法就是使用viewmodel了,以下本人使用viewmodel来实现多表查询的3中方法,
先贴代码再说:
1 第一种是将页面显示多表的数据(也就是汇总各个model表的字段),然后再viewmodel中显示
public class ResultAdList
{
public int A_Id;
public string A_userid;
public int B_Id;
public string B_typename;
}
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
};
} }
public ActionResult Index()
{
return View("Index", new AdRepository());
}
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Dmj.Models.AdRepository>" %> <% foreach (var item in Model.AdList) { %>
<% } %>
接着第二中方法:
public class demoshopViewModels { public IEnumerable<商店> shop { get; set; } public IEnumerable<演示> demo { get; set; } }
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图
目测三种方法都差不多,只有细微的差别,个人觉得第三中最简单也是最常用的