学用MVC4做网站五:5.6文章浏览(前台)
今天做文章的前台文章列表。
前台显示比较简单只显示文章标题和发布日期。
首先添加CommonModelController
using Ninesky.Models; using Ninesky.Repository; using System.Web.Mvc; namespace Ninesky.Controllers { public class CommonModelController : Controller { private CommonModelRepository cModelRsy; public CommonModelController() { cModelRsy = new CommonModelRepository(); } } }
在CommonModelController中声明了CommonModelRepository类cModelRsy。
添加一个分部视图PartialList用来显示内容列表,与“我的文章”相似依然用到CommonModelRepository.List函数
/// <summary> /// 内容列表 /// </summary> /// <param name="id">栏目Id</param> /// <param name="cChildren">是否包含子栏目</param> /// <param name="page">页码</param> /// <param name="pageSize">每页显示的数目【0表示依栏目设置,如栏目不存在设为20】</param> /// <param name="order">排序【0依栏目设置或默认】</param> /// <param name="view">视图</param> public PartialViewResult PartialList(int id, bool cChildren = false, int page = 1, int pageSize = 0, int order = 0, string view = "PartialList") { if (!cChildren && ((pageSize == 0) || (order == 0))) { CategoryRepository _categoryRsy = new CategoryRepository(); var _category = _categoryRsy.Find(id); if (_category != null) { if (pageSize == 0) pageSize = (int)_category.PageSize; if (order == 0) order = _category.Order; } else if (pageSize == 0) pageSize = 20; } var _cModelPd = cModelRsy.List(id, cChildren, null, null, page, pageSize, order); return PartialView(view,_cModelPd); }
代码很简单,参数的含义也都比较清楚。
在PartialList上右键添加视图,视图内部用foreach循环生成文章标题列表。
@model PagerData<Ninesky.Models.CommonModel> <div class="cModel_List"> <ul> @foreach (var item in Model) { <li>@Html.ActionLink(item.Title, "Index", "CommonModel", new { id = item.CommonModelId }, null) <time>@item.ReleaseDate.ToString("yyyy-MM-dd")</time></li> } </ul> </div> @Html.Pager(this.ViewContext.RouteData.Values, Model.Config, "pager", "pager")
好,见证奇迹的时刻到了!打开Views/category/index.cshtml在<div class="content_cnt">。。。</div>里面后部添加@Html.Action("PartialList", "CommonModel", new { id = Model.CategoryId })
整个视图如下:
@model Ninesky.Models.Category @{ ViewBag.Title = "栏目默认页"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="banner"> <img src="~/Content/Default/Images/banner.jpg" /> </div> <div class="left"> <div class="children"> <dl> <dt>@Model.Name</dt> <dd>@Html.Action("PartialChildren", "Category", new { id = Model.CategoryId })</dd> </dl> </div> </div> <div class="content_cnt"> <div class="path">@Html.Action("PartialPath", "Category", new { id = Model.CategoryId })</div> @Html.Action("PartialList", "CommonModel", new { id = Model.CategoryId }) </div>
F5浏览器中看下效果。
代码见:学用MVC4做网站五:文章