mvc 一個View顯示多個Model

來源:互聯網
上載者:User

標籤:.net   mvc   

今天做到這個,記錄一下。

解決的辦法是。定義一個class:viewModel。把要顯示的model放進去。

Controller:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcService.Models;namespace MvcService.Controllers{    public class viewModel    {        public List<New> news { get; set; }        public List<Category> categories { get; set; }        public viewModel(List<New> newsList, List<Category> categoriesList)        {            this.news = newsList;            this.categories = categoriesList;        }    }    public class HomeController : Controller    {        private ServiceEntities db = new ServiceEntities();        public ActionResult Index()        {            var vm = new viewModel(db.News.ToList(), db.Categories.ToList());            vm.news = (from n in db.News                       where n.isDel == false && n.state == true                       orderby n.createTime descending                       select n).Take(16).ToList();            vm.categories = (from n in db.Categories                             where n.pId == 0 && n.isDel == false && n.state == true                             select n).ToList();            return View(vm);        }    }
View:

@using MvcService.Models@model MvcService.Controllers.viewModel //引用HomeControllers中自訂的viewModel@{    ViewBag.Title = "Index";    Layout = "~/Views/Shared/_IndexLayout.cshtml";}<div class="main_1">    <h2>熱點問題</h2>    <ul>        @if (Model != null)        {            foreach (var n in Model.news)            {            <li><a href="~/home/newsdetails">@(n.title.Length > 25 ? n.title.Substring(0, 25) + "..." : n.title)</a> </li>            }        }    </ul>    <div class="clear"></div></div><!--main_1結束--><div class="main_2">    @if (Model != null)    {        foreach (var c in Model.categories)        {        <dl>            <dt>@c.name</dt>            <dd>                <a href="~/home/newslist">會員資訊</a>                 <a href="~/home/newslist">註冊及登入</a>            </dd>        </dl>        }    }</div><!--main_2結束-->
附上.


還有一個問題,我想橙色的顯示該類別的子類別。要怎麼寫。。大神指導下。。

我給出category的表結構。  pId = 0 代表的是父級菜單。



mvc 一個View顯示多個Model

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.