MVC 母版页和部分页面
大体框架
新建一空页面 编辑模版页
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 页面