修改文章是網站必不可少的內容,在我的文章里,文章列表后面操作欄有【修改】鏈接,點擊調轉到[UserEdit]Action,今天來實現這個Action。
還是打開【ArticleController】,添加[UserEdit(int id)]Action這里的id指文章Id。
/// <summary> /// 修改文章 /// </summary> /// <param name="id">文章id</param> [UserAuthorize] public ActionResult UserEdit(int id) { return View(articleRsy.Find(id)); }
@model Ninesky.Models.Article @{ ViewBag.Title = "修改文章"; Layout = "~/Views/Shared/_User.cshtml"; } <div class="workspace"> <div class="inside"> <div class="notebar"> <img alt="" src="~/Content/Default/User/Images/Icon/Article_16.png" />您現在的位置: 修改文章 </div> <div> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <div class="formset"> <dl> <dt>修改文章</dt> <dd> <div class="editor-label"> @Html.HiddenFor(model => model.CommonModelId) @Html.HiddenFor(model => model.CommonModel.CommonModelId) @Html.LabelFor(model => model.CommonModel.CategoryId) (必填) @Html.DisplayDescriptionFor(model => model.CommonModel.CategoryId) </div> <div class="editor-field"> @Html.HiddenFor(model => model.CommonModel.CategoryId) <input type="text" class = "combotree" id="CommonModel_CategoryId_Text" value="@Model.CommonModel.Category.Name" />@Html.ValidationMessageFor(model => model.CommonModel.CategoryId)<br /> <ul id="categorytree" class="ztree comboztree"></ul> </div> </dd> <dd> <div class="editor-label"> @Html.HiddenFor(model => model.ArticleId) @Html.LabelFor(model => model.CommonModel.Title) (必填) @Html.DisplayDescriptionFor(model => model.CommonModel.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.CommonModel.Title) @Html.ValidationMessageFor(model => model.CommonModel.Title) </div> </dd> <dd> <div class="editor-label"> @Html.LabelFor(model => model.Source)@Html.DisplayDescriptionFor(model => model.Source) </div> <div class="editor-field"> @Html.EditorFor(model => model.Source) @Html.ValidationMessageFor(model => model.Source) </div> </dd> <dd> <div class="editor-label"> @Html.LabelFor(model => model.Intro)@Html.DisplayDescriptionFor(model => model.Intro) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Intro, new { @class = "Intro" }) @Html.ValidationMessageFor(model => model.Intro) </div> </dd> <dd> <div class="editor-label"> @Html.LabelFor(model => model.CommonModel.PicUrl)@Html.DisplayDescriptionFor(model => model.CommonModel.PicUrl) </div> <div class="editor-field"> @Html.EditorFor(model => model.CommonModel.PicUrl) @Html.ValidationMessageFor(model => model.CommonModel.PicUrl) </div> </dd> <dd> <div class="editor-label"> @Html.LabelFor(model => model.CommonModel.Status)@Html.DisplayDescriptionFor(model => model.CommonModel.Status) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CommonModel.Status,Ninesky.Models.CommonModel.ContentStatus) @Html.ValidationMessageFor(model => model.CommonModel.Status) </div> </dd> <dd> <div class="editor-label"> @Html.LabelFor(model => model.CommonModel.ReleaseDate) (必填) @Html.DisplayDescriptionFor(model => model.CommonModel.ReleaseDate) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.CommonModel.ReleaseDate, new { @class = "datepicker", type = "datetime" }) @Html.ValidationMessageFor(model => model.CommonModel.ReleaseDate) </div> </dd> <dd> <div class="editor-label"> @Html.LabelFor(model => model.Content) (必填) @Html.DisplayDescriptionFor(model => model.Content) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Content, new { @class = "content" }) @Html.ValidationMessageFor(model => model.Content) </div> </dd> <dd> <div class="editor-label"> </div> <div class="editor-field"> <input type="submit" value="確定" /> </div> </dd> <dd> <div class="editor-label"> </div> <div class="editor-field"> </div> </dd> </dl> </div> } </div> </div> </div> <div class="left">@Html.Partial("PartialUserNavMenus")<br /></div> <div class="clear"></div> <script type="text/javascript"> KindEditor.ready(function (K) { K.create('#Content'); }); var setting = { view: { selectedMulti: false }, callback: { onClick: zTreeOnClick } }; $(document).ready(function () { $.post("@Url.Action("JsonUserGeneralTree", "Category")", { model: "Article" }, function (data) { var zTree = $.fn.zTree.init($("#categorytree"), setting, data); zTree.expandAll(true); var node = zTree.getNodeByParam("id", $("#CommonModel_CategoryId").val(), null); zTree.selectNode(node); }); $("#CommonModel_CategoryId_Text").click(function () { $("#categorytree").show(); }); }); function zTreeOnClick(event, treeId, treeNode) { if (treeNode.iconSkin == "canadd") { $("#CommonModel_CategoryId").val(treeNode.id); $("#CommonModel_CategoryId_Text").val(treeNode.name); $("#categorytree").hide(); } else { alert("該欄目不能文章"); } }; $("#CommonModel_ReleaseDate").datepicker({ }) $("input[type='submit']").button(); </script> @section Scripts { @Styles.Render("~/ZtreeCss") @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/Ztree") @Scripts.Render("~/bundles/kindeditor") }
修改文章處理action UserEdit(Article article)
[HttpPost] [UserAuthorize] [ValidateInput(false)] public ActionResult UserEdit(Article article) { //驗證欄目 CategoryRepository _categoryRsy = new CategoryRepository(); var _category = _categoryRsy.Find(article.CommonModel.CategoryId); if (_category == null) ModelState.AddModelError("CommonModel.CategoryId", "欄目不存在"); if (_category.Model != "Article") ModelState.AddModelError("CommonModel.CategoryId", "該欄目不能添加文章!"); article.CommonModel.Inputer = UserController.UserName; ModelState.Remove("CommonModel.Inputer"); article.CommonModel.Model = "Article"; ModelState.Remove("CommonModel.Model"); if (ModelState.IsValid) { var _article = articleRsy.Find(article.ArticleId); if (_article == null)//文章不存在 { Error _e = new Error { Title = "文章不存在", Details = "查詢不到ArticleId為【" + article.ArticleId.ToString() + "】的文章", Cause = "文章已被刪除或向服務器提交文章時數據丟失", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("UserOwn", "Article") + "'>我的文章</a>重新操作</li><li>返回<a href='" + Url.Action("UserDefault", "Article") + "'>文章管理首頁</a>。</li><li>聯系網站管理員</li>") }; return RedirectToAction("ManageError", "Prompt", _e); } if (_article.CommonModel.Title != article.CommonModel.Title) _article.CommonModel.Title = article.CommonModel.Title; if (_article.CommonModel.CategoryId != article.CommonModel.CategoryId) _article.CommonModel.CategoryId = article.CommonModel.CategoryId; if (article.CommonModel.ReleaseDate != null) _article.CommonModel.ReleaseDate = article.CommonModel.ReleaseDate; if (article.CommonModel.Status != _article.CommonModel.Status) _article.CommonModel.Status = article.CommonModel.Status; if (article.CommonModel.PicUrl != null) _article.CommonModel.PicUrl = article.CommonModel.PicUrl; if (article.CommonModel.CommentStatus != _article.CommonModel.CommentStatus) _article.CommonModel.CommentStatus = article.CommonModel.CommentStatus; if (article.Source != null) _article.Source = article.Source; if (article.Author != null) _article.Author = article.Author; if (article.Intro != null) _article.Intro = article.Intro; _article.Content = article.Content; if (articleRsy.Update(_article)) { Notice _n = new Notice { Title = "修改文章成功", Details = "您已經成功修改了[" + article.CommonModel.Title + "]文章!", DwellTime = 5, NavigationName = "我的文章", NavigationUrl = Url.Action("UserOwn", "Article") }; return RedirectToAction("UserNotice", "Prompt", _n); } else { Error _e = new Error { Title = "修改文章失敗", Details = "在修改文章時,未能保存到數據庫", Cause = "系統錯誤", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("UserAdd", "Article", new { id = article.ArticleId }) + "'>修改文章</a>頁面,輸入正確的信息后重新操作</li><li>返回<a href='" + Url.Action("UserDefault", "Article") + "'>文章管理首頁</a>。</li><li>聯系網站管理員</li>") }; return RedirectToAction("ManageError", "Prompt", _e); } } return View(article); }
這個action也是先驗證欄目是否存在,且能添加文章。呵呵,跟添加文章的基本類似。
按F5 瀏覽器修改篇文章看,能夠修改,ok!
===========================
代碼見:學用MVC4做網站五:文章
===========================
1月26日修改:
今天仔細看的時候發現一個問題。在“我的文章”修改鏈接代碼為:@Html.ActionLink("修改","UserEdit",new {id = item.CommonModelId}),這里的id是公共模型的id,再看看ActionResult UserEdit(int id)里面的代碼,文章是articleRsy.Find(id))查詢返回的。轉到定義看看一下代碼。
/// <summary> /// 查找文章 /// </summary> /// <param name="Id">文章id</param> /// <returns></returns> public override Article Find(int Id) { return dbContext.Articles.AsNoTracking().Include("CommonModel").SingleOrDefault(a => a.ArticleId == Id); }
這里的id是文章id。所以是用驢唇對了馬嘴.... ....
怎么改正呢?既然ActionResult UserEdit(int id)的id指的是公共模型的id,那就寫個根據公共模型id查找文章的函數FindByCommonModelId(int commonModelId)就行了。
在ArticleRepository中添加FindByCommonModelId(int commonModelId)函數。
/// <summary> /// 根據公共模型id查找文章 /// </summary> /// <param name="commonModelId">公共模型Id</param> /// <returns>文章</returns> public Article FindByCommonModelId(int commonModelId) { return dbContext.Articles.AsNoTracking().Include("CommonModel").SingleOrDefault(a => a.CommonModelId == commonModelId); }
將UserEdit(int id)中的return View(articleRsy.Find(id))改為return View(articleRsy.FindByCommonModelId(id))
/// <summary> /// 修改文章 /// </summary> /// <param name="id">公共模型id</param> [UserAuthorize] public ActionResult UserEdit(int id) { return View(articleRsy.FindByCommonModelId(id)); }