ASP.NET MVC5網(wǎng)站開(kāi)發(fā)修改及刪除文章(十)
上次做了顯示文章列表,再實(shí)現(xiàn)修改和刪除文章這部分內(nèi)容就結(jié)束了,這次內(nèi)容比較簡(jiǎn)單,由于做過(guò)了添加文章,修改文章非常類(lèi)似,就是多了一個(gè)TryUpdateModel部分更新模型數(shù)據(jù)。
一、刪除文章
由于公共模型跟,文章,附件有關(guān)聯(lián),所以這里的刪除次序很重要,如果先刪除模型,那么文章ModelID和附件的ModelID多會(huì)變成null,所以要先先刪除文章和附件再刪除公共模型。
由于公共模型和附件是一對(duì)多的關(guān)系,我們把刪除公共模型和刪除附件寫(xiě)在一起。
在BLL的BaseRepository類(lèi)中有默認(rèn)的Delete方法,但這個(gè)方法中僅刪除模型,不會(huì)刪除外鍵,所以在CommonModelRepository在new一個(gè)出來(lái)封印掉默認(rèn)的方法。
public new bool Delete(Models.CommonModel commonModel, bool isSave = true) { if (commonModel.Attachment != null) nContext.Attachments.RemoveRange(commonModel.Attachment); nContext.CommonModels.Remove(commonModel); return isSave ? nContext.SaveChanges() > 0 : true; }
這個(gè)的意思是封印掉繼承的Delete方法,在新的方法中如果存在附加那么先刪除附件,再刪除公共模型。那么如果我們還想調(diào)用基類(lèi)的Delete方法怎么辦?可以用base.Delete。
好了,現(xiàn)在可以開(kāi)始刪除了。
在ArticleController中添加Delete方法
/// <summary> /// 刪除 /// </summary> /// <param name="id">文章id</param> /// <returns></returns> public JsonResult Delete(int id) { //刪除附件 var _article = articleService.Find(id); if(_article == null) return Json(false); //附件列表 var _attachmentList = _article.CommonModel.Attachment; var _commonModel = _article.CommonModel; //刪除文章 if (articleService.Delete(_article)) { //刪除附件文件 foreach (var _attachment in _attachmentList) { System.IO.File.Delete(Server.MapPath(_attachment.FileParth)); } //刪除公共模型 commonModelService.Delete(_commonModel); return Json(true); } else return Json(false); }
二、修改文章
這個(gè)部分跟添加文章非常類(lèi)似
首先在ArticleController中添加顯示編輯視圖的Edit
/// <summary> /// 修改 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult Edit(int id) { return View(articleService.Find(id)); }
右鍵添加視圖,這個(gè)跟添加類(lèi)似,沒(méi)什么好說(shuō)的直接上代碼
@section scripts{ <script type="text/javascript" src="~/Scripts/KindEditor/kindeditor-min.js"></script> <script type="text/javascript"> //編輯框 KindEditor.ready(function (K) { window.editor = K.create('#Content', { height: '500px', uploadJson: '@Url.Action("Upload", "Attachment")', fileManagerJson: '@Url.Action("FileManagerJson", "Attachment", new { id = @Model.CommonModel.ModelID })', allowFileManager: true, formatUploadUrl: false }); //首頁(yè)圖片 var editor2 = K.editor({ fileManagerJson: '@Url.Action("FileManagerJson", "Attachment", new {id=@Model.CommonModel.ModelID })' }); K('#btn_picselect').click(function () { editor2.loadPlugin('filemanager', function () { editor2.plugin.filemanagerDialog({ viewType: 'VIEW', dirName: 'image', clickFn: function (url, title) { var url; $.ajax({ type: "post", url: "@Url.Action("CreateThumbnail", "Attachment")", data: { originalPicture: url }, async: false, success: function (data) { if (data == null) alert("生成縮略圖失?。?); else { K('#CommonModel_DefaultPicUrl').val(data); K('#imgpreview').attr("src", data); } editor2.hideDialog(); } }); } }); }); }); }); </script> } @model Ninesky.Models.Article @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal" role="form"> <h4>添加文章</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> <label class="control-label col-sm-2" for="CommonModel_CategoryID">欄目</label> <div class="col-sm-10"> <input id="CommonModel_CategoryID" name="CommonModel.CategoryID" data-options="url:'@Url.Action("JsonTree", "Category", new { model="Article" })'" class="easyui-combotree" style="height: 34px; width: 280px;" value="@Model.CommonModel.CategoryID" /> @Html.ValidationMessageFor(model => model.CommonModel.CategoryID)</div> </div> <div class="form-group"> @Html.LabelFor(model => model.CommonModel.Title, new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.TextBoxFor(model => model.CommonModel.Title, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.CommonModel.Title)</div> </div> <div class="form-group"> @Html.LabelFor(model => model.Author, new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.TextBoxFor(model => model.Author, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Author) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Source, new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.TextBoxFor(model => model.Source, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Source) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Intro, new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.TextAreaFor(model => model.Intro, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Intro) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Content, new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.EditorFor(model => model.Content) @Html.ValidationMessageFor(model => model.Content) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.CommonModel.DefaultPicUrl, new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> <img id="imgpreview" class="thumbnail" src="@Model.CommonModel.DefaultPicUrl" /> @Html.HiddenFor(model => model.CommonModel.DefaultPicUrl) <a id="btn_picselect" class="easyui-linkbutton">選擇…</a> @Html.ValidationMessageFor(model => model.CommonModel.DefaultPicUrl) </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" value="保存" class="btn btn-default" /> </div> </div> </div> }
開(kāi)始做后臺(tái)接受代碼,在ArticleController中添加如下代碼。
[HttpPost] [ValidateInput(false)] [ValidateAntiForgeryToken] public ActionResult Edit() { int _id = int.Parse(ControllerContext.RouteData.GetRequiredString("id")); var article = articleService.Find(_id); TryUpdateModel(article, new string[] { "Author", "Source", "Intro", "Content" }); TryUpdateModel(article.CommonModel, "CommonModel", new string[] { "CategoryID", "Title", "DefaultPicUrl" }); if(ModelState.IsValid) { if (articleService.Update(article)) { //附件處理 InterfaceAttachmentService _attachmentService = new AttachmentService(); var _attachments = _attachmentService.FindList(article.CommonModel.ModelID, User.Identity.Name, string.Empty,true).ToList(); foreach (var _att in _attachments) { var _filePath = Url.Content(_att.FileParth); if ((article.CommonModel.DefaultPicUrl != null && article.CommonModel.DefaultPicUrl.IndexOf(_filePath) >= 0) || article.Content.IndexOf(_filePath) > 0) { _att.ModelID = article.ModelID; _attachmentService.Update(_att); } else { System.IO.File.Delete(Server.MapPath(_att.FileParth)); _attachmentService.Delete(_att); } } return View("EditSucess", article); } } return View(article); }
詳細(xì)講解一下吧:
1、[ValidateInput(false)] 表示不驗(yàn)證輸入內(nèi)容。因?yàn)槲恼聝?nèi)容包含html代碼,防止提交失敗。
2、[ValidateAntiForgeryToken]是為了防止偽造跨站請(qǐng)求的,也就說(shuō)只有本真的請(qǐng)求才能通過(guò)。
見(jiàn)圖中的紅線部分,在試圖中構(gòu)造驗(yàn)證字符串,然后再后臺(tái)驗(yàn)證。
3、public ActionResult Edit()??催@個(gè)方法沒(méi)有接收任何數(shù)據(jù),我們?cè)俜椒ㄖ惺褂肨ryUpdateModel更新模型。因?yàn)椴荒芡耆嘈庞脩?hù),比如如果用戶(hù)構(gòu)造一個(gè)CateggoryID過(guò)來(lái),就會(huì)把文章發(fā)布到其他欄目去。
這個(gè)是在路由中獲取id參數(shù)
再看這兩行,略有不同
第一行直接更新article模型。第一個(gè)參數(shù)是要更新的模型,第二個(gè)參數(shù)是更新的字段。
第二行略有不同,增加了一個(gè)前綴參數(shù),我們看視圖生成的代碼 @Html.TextBoxFor(model => model.CommonModel.Title 是帶有前綴CommonModel的。所以這里必須使用前綴來(lái)更新視圖。
三、修改文章列表
寫(xiě)完文章后,就要更改文章列表代碼用來(lái)刪除和修改文章。
打開(kāi)List視圖,修改部分由2處。
1、js腳本部分
<script type="text/javascript"> $("#article_list").datagrid({ loadMsg: '加載中……', pagination:true, url: '@Url.Action("JsonList","Article")', columns: [[ { field: 'ModelID', title: 'ID', checkbox: true }, { field: 'CategoryName', title: '欄目'}, { field: 'Title', title: '標(biāo)題'}, { field: 'Inputer', title: '錄入', align: 'right' }, { field: 'Hits', title: '點(diǎn)擊', align: 'right' }, { field: 'ReleaseDate', title: '發(fā)布日期', align: 'right', formatter: function (value, row, index) { return jsonDateFormat(value); } }, { field: 'StatusString', title: '狀態(tài)', width: 100, align: 'right' } ]], toolbar: '#toolbar', idField: 'ModelID', onDblClickRow: function (rowIndex, rowData) { window.parent.addTab("修改文章", "@Url.Action("Edit","Article")/" + rowData.ModelID, "icon-page"); } }); //查找 $("#btn_search").click(function () { $("#article_list").datagrid('load', { title: $("#textbox_title").val(), input: $("#textbox_inputer").val(), category: $("#combo_category").combotree('getValue'), fromDate: $("#datebox_fromdate").datebox('getValue'), toDate: $("#datebox_todate").datebox('getValue') }); }); //修改事件 function eidt() { var rows = $("#article_list").datagrid("getSelections"); if (!rows || rows.length < 1) { $.messager.alert("提示", "請(qǐng)選擇要修改的行!"); return; } else if (rows.length != 1) { $.messager.alert("提示", "僅能選擇一行!"); return; } else { window.parent.addTab("修改文章", "@Url.Action("Edit","Article")/" + rows[0].ModelID, "icon-page"); } } //刪除 function del() { var rows = $("#article_list").datagrid("getSelections"); if (!rows || rows.length < 1) { $.messager.alert("提示", "未選擇任何行!"); return; } else if (rows.length > 0) { $.messager.confirm("確認(rèn)", "您確定要?jiǎng)h除所選行嗎?", function (r) { if (r) { $.messager.progress(); $.each(rows, function (index, value) { $.ajax({ type: "post", url: "@Url.Action("Delete", "Article")", data: { id: value.ModelID }, async: false, success: function (data) { } }); }); $.messager.progress('close'); //清除選擇行 rows.length = 0; $("#article_list").datagrid('reload'); } }); return; } } </script>
增加了修改方法、刪除方法,在datagrid里添加行雙擊進(jìn)入修改視圖的方法
onDblClickRow: function (rowIndex, rowData) { window.parent.addTab("修改文章", "@Url.Action("Edit","Article")/" + rowData.ModelID, "icon-page"); }
2、
四、我的文章列表
我的文章列表與全部文章類(lèi)似,并簡(jiǎn)化掉了部分內(nèi)容那個(gè),更加簡(jiǎn)單,直接上代碼了
Article控制器中添加
/// <summary> /// 文章列表Json【注意權(quán)限問(wèn)題,普通人員是否可以訪問(wèn)?】 /// </summary> /// <param name="title">標(biāo)題</param> /// <param name="input">錄入</param> /// <param name="category">欄目</param> /// <param name="fromDate">日期起</param> /// <param name="toDate">日期止</param> /// <param name="pageIndex">頁(yè)碼</param> /// <param name="pageSize">每頁(yè)記錄</param> /// <returns></returns> public ActionResult JsonList(string title, string input, Nullable<int> category, Nullable<DateTime> fromDate, Nullable<DateTime> toDate, int pageIndex = 1, int pageSize = 20) { if (category == null) category = 0; int _total; var _rows = commonModelService.FindPageList(out _total, pageIndex, pageSize, "Article", title, (int)category, input, fromDate, toDate, 0).Select( cm => new Ninesky.Web.Models.CommonModelViewModel() { CategoryID = cm.CategoryID, CategoryName = cm.Category.Name, DefaultPicUrl = cm.DefaultPicUrl, Hits = cm.Hits, Inputer = cm.Inputer, Model = cm.Model, ModelID = cm.ModelID, ReleaseDate = cm.ReleaseDate, Status = cm.Status, Title = cm.Title }); return Json(new { total = _total, rows = _rows.ToList() }); } public ActionResult MyList() { return View(); } /// <summary> /// 我的文章列表 /// </summary> /// <param name="title"></param> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public ActionResult MyJsonList(string title, Nullable<DateTime> fromDate, Nullable<DateTime> toDate, int pageIndex = 1, int pageSize = 20) { int _total; var _rows = commonModelService.FindPageList(out _total, pageIndex, pageSize, "Article", title, 0, string.Empty, fromDate, toDate, 0).Select( cm => new Ninesky.Web.Models.CommonModelViewModel() { CategoryID = cm.CategoryID, CategoryName = cm.Category.Name, DefaultPicUrl = cm.DefaultPicUrl, Hits = cm.Hits, Inputer = cm.Inputer, Model = cm.Model, ModelID = cm.ModelID, ReleaseDate = cm.ReleaseDate, Status = cm.Status, Title = cm.Title }); return Json(new { total = _total, rows = _rows.ToList() }, JsonRequestBehavior.AllowGet); } 為MyList右鍵添加視圖 <div id="toolbar"> <div> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true" onclick="eidt()">修改</a> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="del()">刪除</a> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload',plain:true" onclick="$('#article_list').datagrid('reload');">刷新</a> </div> <div class="form-inline"> <label>標(biāo)題</label> <input id="textbox_title" class="input-easyui" style="width:280px" /> <label>添加日期</label> <input id="datebox_fromdate" type="datetime" class="easyui-datebox" style="width:120px" /> - <input id="datebox_todate" type="datetime" class="easyui-datebox" style="width:120px; " /> <a href="#" id="btn_search" data-options="iconCls:'icon-search'" class="easyui-linkbutton">查詢(xún)</a> </div> </div> <table id="article_list"></table> <script src="~/Scripts/Common.js"></script> <script type="text/javascript"> $("#article_list").datagrid({ loadMsg: '加載中……', pagination:true, url: '@Url.Action("MyJsonList", "Article")', columns: [[ { field: 'ModelID', title: 'ID', checkbox: true }, { field: 'CategoryName', title: '欄目'}, { field: 'Title', title: '標(biāo)題'}, { field: 'Inputer', title: '錄入', align: 'right' }, { field: 'Hits', title: '點(diǎn)擊', align: 'right' }, { field: 'ReleaseDate', title: '發(fā)布日期', align: 'right', formatter: function (value, row, index) { return jsonDateFormat(value); } }, { field: 'StatusString', title: '狀態(tài)', width: 100, align: 'right' } ]], toolbar: '#toolbar', idField: 'ModelID', onDblClickRow: function (rowIndex, rowData) { window.parent.addTab("修改文章", "@Url.Action("Edit","Article")/" + rowData.ModelID, "icon-page"); } }); //查找 $("#btn_search").click(function () { $("#article_list").datagrid('load', { title: $("#textbox_title").val(), fromDate: $("#datebox_fromdate").datebox('getValue'), toDate: $("#datebox_todate").datebox('getValue') }); }); //修改事件 function eidt() { var rows = $("#article_list").datagrid("getSelections"); if (!rows || rows.length < 1) { $.messager.alert("提示", "請(qǐng)選擇要修改的行!"); return; } else if (rows.length != 1) { $.messager.alert("提示", "僅能選擇一行!"); return; } else { window.parent.addTab("修改文章", "@Url.Action("Edit","Article")/" + rows[0].ModelID, "icon-page"); } } //刪除 function del() { var rows = $("#article_list").datagrid("getSelections"); if (!rows || rows.length < 1) { $.messager.alert("提示", "未選擇任何行!"); return; } else if (rows.length > 0) { $.messager.confirm("確認(rèn)", "您確定要?jiǎng)h除所選行嗎?", function (r) { if (r) { $.messager.progress(); $.each(rows, function (index, value) { $.ajax({ type: "post", url: "@Url.Action("Delete", "Article")", data: { id: value.ModelID }, async: false, success: function (data) { } }); }); $.messager.progress('close'); //清除選擇行 rows.length = 0; $("#article_list").datagrid('reload'); } }); return; } } </script>
要注意的是刪除文章時(shí)刪除的次序,修改文章時(shí)TryUpdateModel的使用,希望本文對(duì)大家的學(xué)習(xí)有所幫助。
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)管理列表、回復(fù)及刪除(十三)
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)我的咨詢(xún)列表及添加咨詢(xún)(十二)
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)添加文章(八)
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)文章管理架構(gòu)(七)
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)用戶(hù)修改資料和密碼(六)
- ASP.NET?MVC5網(wǎng)站開(kāi)發(fā)用戶(hù)登錄、注銷(xiāo)(五)
- ASP.NET?MVC5網(wǎng)站開(kāi)發(fā)用戶(hù)注冊(cè)(四)
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)項(xiàng)目框架(二)
- ASP.NET MVC5網(wǎng)站開(kāi)發(fā)概述(一)
- MVC4制作網(wǎng)站教程第三章 刪除用戶(hù)組操作3.4
相關(guān)文章
在?Net7.0?環(huán)境下如何使用?RestSharp?發(fā)送?Http(FromBody和FromForm)請(qǐng)求
這篇文章主要介紹了在?Net7.0?環(huán)境下使用?RestSharp?發(fā)送?Http(FromBody和FromForm)請(qǐng)求,今天,我就兩個(gè)小的知識(shí)點(diǎn),就是通過(guò)使用?RestSharp?訪問(wèn)?WebAPI,提交?FromBody?和?FromForm?兩種方式的數(shù)據(jù),還是有些區(qū)別的,本文結(jié)合實(shí)例代碼介紹的非常詳細(xì),需要的朋友參考下吧2023-09-09通用?HTTP?簽名組件的另類(lèi)實(shí)現(xiàn)方式
這篇文章主要介紹了通用?HTTP?簽名組件的另類(lèi)實(shí)現(xiàn)方式,實(shí)現(xiàn)思路大概是采用鏈?zhǔn)秸{(diào)用的方式,使得簽名的步驟可以動(dòng)態(tài)拼湊組合,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09MultiLine 換行后實(shí)現(xiàn)讀取不換行的具體思路
輸入內(nèi)容中有換行,保存到數(shù)據(jù)庫(kù),直接查看感覺(jué)沒(méi)有換行,但查詢(xún)結(jié)果“以文本格式顯示結(jié)果”你就會(huì)發(fā)現(xiàn) 其實(shí)是有換行的,下面與大家分享下具體的解決方法2013-06-06ASP.NET實(shí)現(xiàn)個(gè)人信息注冊(cè)頁(yè)面并跳轉(zhuǎn)顯示
這篇文章主要介紹了ASP.NET實(shí)現(xiàn)個(gè)人信息注冊(cè)頁(yè)面并跳轉(zhuǎn)顯示的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12獲取遠(yuǎn)程網(wǎng)頁(yè)的內(nèi)容之二(downmoon原創(chuàng))
獲取遠(yuǎn)程網(wǎng)頁(yè)的內(nèi)容之二(downmoon原創(chuàng))...2007-03-03SignalR中豐富多彩的消息推送方式的實(shí)現(xiàn)代碼
這篇文章主要介紹了SignalR中豐富多彩的消息推送方式的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04