大體框架
新建一空頁面 編輯模版頁
FirstMoBan
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>FirstMoBan</title> <style type="text/css"> .tbhead { margin-top:0; text-align:center; } .tbmowei { text-align:center; margin-top:25%; } .td1 { text-align:center; } </style> </head> <body> <div> <table class="tbhead" width="100%" border="0" cellspacing="0" cellpadding="0" > <tr> <td height="10%" bgcolor="#ffffcc"><img src="~/tupian/ee.jpg" /></td> </tr> </table> <table width="100%" height="60%" > <tr> <td class="td1">@Html.Partial("~/Views/NewsTypePartial.cshtml")</td> <td class="td1">@RenderBody()</td> </tr> </table> <table class="tbmowei" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="10%" bgcolor="#ffffcc">天涯海閣<br />2015-7-11</td> </tr> </table> </div> </body> </html>
控制器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication2.Models; namespace MvcApplication2.Controllers { public class HomeController : Controller { // // GET: /Home/ //主頁面 public ActionResult Index() { return View(); } //國際新聞視圖 public ActionResult ShowGJ() { return View(); } //娛樂新聞視圖 public ActionResult ShowYL() { return View(); } //財經新聞視圖 public ActionResult ShowCJ() { return View(); } //顯示新聞詳細內容視圖 public ActionResult ShowDetails(int id) { News data = new NewsBF().SelectByKey(id); return View(data); } //顯示數據庫查詢出的新聞標題列 public ActionResult ShowNewsIndexPartial(string newsType) { ViewBag.Data = new NewsBF().Select(newsType); return PartialView(); } } }
母版頁中@Html.Partial 創建部分頁面 編輯
NewsTypePartial.cshtml
<h2>新聞類型</h2> <div> @Html.ActionLink("國內新聞","Index","Home")<br/> @Html.ActionLink("國際新聞","ShowGJ","Home")<br/> @Html.ActionLink("娛樂新聞","ShowYL","Home")<br/> @Html.ActionLink("財經新聞","ShowCJ","Home")<br/> </div>
部分頁面中ActionLink超鏈接指向Home控制器中的Index,ShowGJ,ShowYL,ShowCJ動作,分別添加視圖,都與Index相同,修改一下Type與數據庫對應即可
母版中@RenderBody() 在Index中編輯
@{ ViewBag.Title = "Index"; Layout = "~/Views/FirstMoBan.cshtml"; } <h2>國內新聞</h2> @Html.Action("ShowNewsIndexPartial", new { newsType="0" })
Index中 Action轉到控制器動作ShowNewsIndexPartial,添加ShowNewsIndexPartial動作的視圖
ShowNewsIndexPartial視圖
@using MvcApplication2.Models; @{ List<News> list =ViewBag.Data as List<News>; } <ul> @foreach(News data in list){ <li> @Html.ActionLink(data.title, "ShowDetails", "Home", new{id=data.ids }, null); </li> } </ul>
ShowNewsIndexPartial視圖中ActionLink超鏈接 鏈接到Home控制器的ShowDetails動作,添加ShowDetails動作的視圖
ShowDetails視圖
@using MvcApplication2.Models; @model News @{ ViewBag.Title = "ShowDetails"; Layout = "~/Views/FirstMoBan.cshtml"; } @{ if(Model != null) { <h2>@Model.title</h2> <div>@Model.memo</div> } else { <div>未找到相關數據</div> } }
運行效果:
Index 頁面