首页 > 代码库 > mvc 一个View显示多个Model

mvc 一个View显示多个Model

今天做到这个,记录一下。

解决的办法是。定义一个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=http://www.mamicode.com/"~/home/newsdetails">@(n.title.Length > 25 ? n.title.Substring(0, 25) + "..." : n.title) >附上效果图.


还有一个问题,我想橙色的显示该类别的子类别。要怎么写。。大神指导下。。

我给出category的表结构。  pId = 0 代表的是父级菜单。



mvc 一个View显示多个Model