码迷,mamicode.com
首页 > Web开发 > 详细

mvc 一个View显示多个Model

时间:2014-12-04 18:07:42      阅读:758      评论:0      收藏:0      [点我收藏+]

标签:.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结束-->
附上效果图.

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

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

bubuko.com,布布扣bubuko.com,布布扣


mvc 一个View显示多个Model

标签:.net   mvc   

原文地址:http://blog.csdn.net/ycwol/article/details/41725419

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!