前面做好了瀏覽文章目錄,現在開始做顯示文章內容。
打開CommonModelController,添加一個Index(int id) action。action中先查找指定Id的內容是否存在。存在就返回視圖;不存在返回錯誤頁面。
/// <summary> /// 顯示內容 /// </summary> /// <param name="id">公共模型Id</param> public ActionResult Index(int id) { var _cModel = cModelRsy.Find(id); if (_cModel == null) { Error _e = new Error { Title = "內容不存在", Details = "未能從數據庫中找到指定的內容!", Cause = "該內容已經被刪除。", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("Index", "Home") + "'>網站首頁</a>。</li>") }; return RedirectToAction("ManageError", "Prompt", _e); } return View(_cModel.Category.ContentView,_cModel); }
右鍵添加視圖。
@model Ninesky.Models.CommonModel @{ ViewBag.Title = Model.Title + "—" + Model.Category.Name; 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.Category.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> <div class="content"> 這里是文章內容 </div> </div>
實際上就是從views/category/index.cshtml復制過來,稍微修改一下。關鍵是<div class="content"> …</div>,這個里面我計划用來顯示文章內容。CommonModel里面只有文章的公共信息,沒有具體內容,要從ArticleController中調用。
打開ArticleController,添加PartialDetail(int id, string view = "PartialDetail")action。從名字可以看出來這里是做顯示分部視圖用,id是公共模型id,view是視圖名稱,可以根據需要傳遞不同的視圖名,默認為"PartialDetail"。
/// <summary> /// 文章內容 /// </summary> /// <param name="id">CommonModelId</param> /// <param name="view">視圖</param> public PartialViewResult PartialDetail(int id, string view = "PartialDetail") { return PartialView(view, articleRsy.FindByCModelId(id)); }
右鍵添加分部視圖
@model Ninesky.Models.Article <div class="title">@Model.CommonModel.Title</div> <div class="Info">來源:@Model.Source 作者:@Model.Author 發布時間:@Model.CommonModel.ReleaseDate.ToLongDateString() 閱讀:@Model.CommonModel.Hits </div> <div class="text">@Html.Raw(Model.Content)</div>
視圖的頂部顯示標題,隨后顯示文章的基本信息,底部顯示文章內容。文章內容一定要用@Html.Raw()用來顯示HTML內容。如果直接寫@Model.Content 顯示出來會是HTML編碼后的內容。
返回到CommonModel/index.chhtml視圖將“這里是文章內容”替換為@Html.Action("PartialDetail", "Article", new { id = Model.CommonModelId })。
到這里就可以顯示文章內容,但是文章內容的Url顯示格式為“http://localhost:52270/CommonModel/Index/10” 這種格式看起來不是太友好。我希望url盡量短且好理解、好記。怎么辦?改路由。
打開App_Start/RouteConfig.cs,在默認路由的上面加一條名稱為“Item”的路由,url格式為"Items/{id}"。
routes.MapRoute( name: "Items", url: "Items/{id}", defaults: new { controller = "CommonModel", action = "Index", id = UrlParameter.Optional } );
這個url就比較順眼了。“/CommonModel/Index/10”將會表示為“/Items/10”。
F5 瀏覽器中看下效果。
============================================
代碼見:學用MVC4做網站五:文章
============================================
感謝您一直的關心和幫助,祝您新年快樂,合家歡樂!