我不擅长写博客...内容尽量简单吧..仅作示例.. asp.net MVC中,一次默认只能返回一个Model,如果调用多个数据集,只能用ViewData来导来导去,好像很麻烦,所以,可以给model扩展方法来实现...我只是入门学习者,可能不太懂,也描述的不太清楚,如果能有更好的方法或建议..
首先,在控制器中定义一个类,内容如下:
Code
public class lviewModel { public List<Sorts> sortList { get; private set; } public List<Articles> artList { get; private set; } public lviewModel(List<Models.Sorts> sortlists, List<Models.Articles> artlists) { this.sortList = sortlists; this.artList = artlists; } }
以此来接收两个list,然后 返回的时候 Models.ESCMSContext escms = new ESCMS_MVC_SQL.Models.ESCMSContext();
return View(new lviewModel(escms.sortList(), escms.artList()));
在使用的时候 视图文件的第一行要引用
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ESCMS_MVC_SQL.Controllers.lviewModel>" %>
ESCMS_MVC_SQL改成你项目的名称
然后就可以
Model.artList Model.sortList
这样来用了
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <form id="form1" runat="server"> <h2>list</h2> <table> <tr> <th></th> <th> ArtID </th> <th> ArtTitle </th> <th> ArtSort </th> <th> ArtSort </th> </tr> <% foreach (var item in Model.artList) { %> <tr> <td> <%= Html.ActionLink("Edit", "Edit", new { id=item.ArtID }) %> | <%= Html.ActionLink("Details", "Details", new { id=item.ArtID })%> </td> <td> <%= Html.Encode(item.ArtID) %> </td> <td> <%= Html.Encode(item.ArtTitle) %> </td> <td> <%= Html.Encode(item.ArtSort) %> </td> <td> <%= Html.Encode(item.Sorts.SortName) %> </td> </tr> <% } %> </table> <table> <tr> <th>aa</th> <th>bb</th> </tr> <% foreach (var item in Model.sortList) { %> <tr> <td> <%= Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> | <%= Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%> </td> <td> <%= Html.Encode(item.SortName) %> </td> </tr> <% } %> </table> </form> </asp:Content>
这样就可以了..还算简单,就是之前有些绕...我觉得微软应默认提供这样的类,写起来才方便.. |
|
来自: ThinkTank_引擎 > 《MVC》