.net mvc4 一个 view 显示多个 model

本文记录了在.NET MVC4中如何通过创建ViewModel类来整合并显示多个Model的数据。Controller部分需要将各Model封装进ViewModel。同时,文章探讨了如何根据类别显示其子类别,涉及数据库表结构及后期解决方案,最终采用了ViewBag和自定义Cate.cs类来实现。
摘要由CSDN通过智能技术生成

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

解决的办法是。定义一个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:
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值