ASP.NET MVC 同一view返回多个Model或数据集的方法
Asp.net MVC中,一次默认只能返回一个Model,如果调用多个数据集,只能用ViewData来导来导去,好像很麻烦,所以,可以给model扩展方法来实现(声明一下:这方法只针对MVC2之前,MVC3之后已支持泛类型,直接使用ViewBag传过去即可,非常方便的。)
首先,在控制器中定义一个类,内容如下:
public class blogModel
{
public IQueryable<T_Type> types { get; private set; }
public IQueryable<T_Post> posts { get; private set; }
public blogModel(IQueryable<T_Type> types, IQueryable<T_Post> posts)
{
this.types = types;
this.posts = posts;
}
}
以此来接收两个IQueryable,然后 返回的时候
IQueryable<T_Type> types = from t in cb.T_Type select t;
IQueryable<T_Post> posts = (from p in cb.T_Post orderby p.updateTime select p).Take(10);
//ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View("Index",new blogModel(types,posts));
public class blogModel
{
public IQueryable<T_Type> types { get; private set; }
public IQueryable<T_Post> posts { get; private set; }
public blogModel(IQueryable<T_Type> types, IQueryable<T_Post> posts)
{
this.types = types;
this.posts = posts;
}
}
以此来接收两个IQueryable,然后 返回的时候
IQueryable<T_Type> types = from t in cb.T_Type select t;
IQueryable<T_Post> posts = (from p in cb.T_Post orderby p.updateTime select p).Take(10);
//ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View("Index",new blogModel(types,posts));
视图文件的第一行要引用
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcBlog.Controllers.blogModel>" %>
然后就可以使用types和posts数据集啦!!!
<%--文章类别--%>
<div id="lcategory">
<h4>
<span>我的文章分类</span></h4>
<ul>
<% foreach (var type in Model.types)
{%>
<li><%=Html.ActionLink( type.typeName,"#")%></li>
<%} %>
</ul>
<br />
</div>
<%-- 最近文章--%>
<div id="llatest">
<h4>
<span>最新文章列表</span></h4>
<ul>
<% foreach (var post in Model.posts)
{%>
<li> <%=Html.ActionLink( post.title,"#")%></li>
<%} %>
</ul>
<br />
</div>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcBlog.Controllers.blogModel>" %>
然后就可以使用types和posts数据集啦!!!
<%--文章类别--%>
<div id="lcategory">
<h4>
<span>我的文章分类</span></h4>
<ul>
<% foreach (var type in Model.types)
{%>
<li><%=Html.ActionLink( type.typeName,"#")%></li>
<%} %>
</ul>
<br />
</div>
<%-- 最近文章--%>
<div id="llatest">
<h4>
<span>最新文章列表</span></h4>
<ul>
<% foreach (var post in Model.posts)
{%>
<li> <%=Html.ActionLink( post.title,"#")%></li>
<%} %>
</ul>
<br />
</div>