學用MVC4做網站五:5.4刪除文章


前幾天把添加、修改功能都做了,今天開始寫刪除功能。刪除文章既要刪除文章本身同時也要在公共模型中刪除對應項。

首先寫從數據庫中刪除文章的函數。打開ArticleRepository修改Delete的函數。有上次的教訓這次明白了傳遞的id應該是公共模型id。

/// <summary>
        /// 刪除文章
        /// </summary>
        /// <param name="commonModelId">公共模型id</param>
        /// <returns></returns>
        public override bool Delete(int commonModelId)
        {
            dbContext.CommonModels.Remove(dbContext.CommonModels.SingleOrDefault(cM => cM.CommonModelId == commonModelId));
            dbContext.Articles.Remove(dbContext.Articles.SingleOrDefault(a => a.CommonModelId == commonModelId));
            return dbContext.SaveChanges() > 0;
        }

很簡單先在對應的公共模型刪除,再刪除文章,然后保存、返回。

第二步做UserDelete(int id) action。動作中先是ArticleRepository.Delete(id)進行刪除並返回是否成功。然后判斷請求類型:如果是Ajax方式返回是否成功的json類型;否則跳轉到提示頁或錯誤頁。

/// <summary>
        /// 刪除文章
        /// </summary>
        /// <param name="id">公共模型id</param>
        /// <returns></returns>
        [UserAuthorize]
        public ActionResult UserDelete(int id)
        {
            bool _deleted = articleRsy.Delete(id);
            if (Request.IsAjaxRequest())
            {
                return Json(_deleted);
            }
            else
            {
                if (_deleted)
                {
                    Notice _n = new Notice { Title = "刪除文章成功", Details = "您已經成功刪除了該文章!", 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("UserOwn", "Article") + "'>我的文章</a>頁面,輸入正確的信息后重新操作</li><li>返回<a href='" + Url.Action("UserDefault", "Article") + "'>文章管理首頁</a>。</li><li>聯系網站管理員</li>") };
                    return RedirectToAction("ManageError", "Prompt", _e);
                }
            }
        }

第三步開始做刪除的前台。就不單獨寫視圖,直接寫在“我的文章中”。打開UserOwn.cshtml,修改刪除連接的ActionLink為@Html.ActionLink("刪除", "UserDelete", new { id = item.CommonModelId }, new { @class = "btnDel" })

然后寫點擊刪除鏈接的js代碼

<script type="text/javascript">
    $(".btnDel").click(function () {
        if (confirm("你確定要刪除該文章嗎?")) {
            var url = $(this).attr("href");
            $.post(url, null, function (data) {
                if (data) {
                    alert("刪除成功!");
                    window.location.reload();
                }
                else {
                    alert("刪除失敗!");
                }
            });
        }
        return false;
    });
</script>

先提示“你確定要刪除該文章嗎?”,如果確定則采用post方式請求刪除,並返回相應結果給出相應提示。

F5 刪除一下文章看。

無標題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM