標籤:.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