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="~/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 代表的是父级菜单。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。