分享

ASP.net MVC 同一view或页面使用多个Model或数据集的方法

 ThinkTank_引擎 2014-05-27

 我不擅长写博客...内容尽量简单吧..仅作示例.. 

asp.net MVC中,一次默认只能返回一个Model,如果调用多个数据集,只能用ViewData来导来导去,好像很麻烦,所以,可以给model扩展方法来实现...我只是入门学习者,可能不太懂,也描述的不太清楚,如果能有更好的方法或建议..

 

首先,在控制器中定义一个类,内容如下: 

 

复制代码
Code
    public class lviewModel
    {
        public List<Sorts> sortList { getprivate set; }
        public List<Articles> artList { getprivate 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>


 

这样就可以了..还算简单,就是之前有些绕...我觉得微软应默认提供这样的类,写起来才方便..

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多