?
源碼下載地址:http://www.yealuo.com/Sccnn/Detail?KeyValue=c891ffae-7441-4afb-9a75-c5fe000e3d1c?
素材管理模塊也是我們這個項目的核心模塊,里面的增刪查改都跟文章管理模塊相同或者相似,唯一不同點可能是對附件的上傳處理,但沒有涉及到復雜的文件上傳,所以我們采用了原生的文件流的形式上傳,同時在做了文件在編輯的時候,如果重新上傳文件,我們將舊文件刪除,這樣可以釋放更多的服務器空間,以免造成大量垃圾文件堆積。
在創建之前,我們需要在表現層的SystemExtension下創建一個公共類BaseCommon.cs:
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Web;namespace IA.WebApp.SystemExtension {/// <summary>/// 通用方法/// </summary>public class BaseCommon{#region 解壓ZIP文件/// <summary> /// 解壓功能(解壓壓縮文件到指定目錄) /// </summary> /// <param name="fileToUnZip">待解壓的文件</param> /// <param name="zipedFolder">指定解壓目標目錄</param> /// <param name="password">密碼</param> /// <returns>解壓結果</returns> public static bool UnZip(string fileToUnZip, string zipedFolder, string password){bool result = true;FileStream fs = null;ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = null;ICSharpCode.SharpZipLib.Zip.ZipEntry ent = null;string fileName;if (!File.Exists(fileToUnZip))return false;if (!Directory.Exists(zipedFolder))Directory.CreateDirectory(zipedFolder);try{zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(fileToUnZip));if (!string.IsNullOrEmpty(password)) zipStream.Password = password;while ((ent = zipStream.GetNextEntry()) != null){if (!string.IsNullOrEmpty(ent.Name)){fileName = Path.Combine(zipedFolder, ent.Name);fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi if (fileName.EndsWith("\\")){Directory.CreateDirectory(fileName);continue;}fs = File.Create(fileName);int size = 2048;byte[] data = new byte[size];while (true){size = zipStream.Read(data, 0, data.Length);if (size > 0)fs.Write(data, 0, size);elsebreak;}}}}catch{result = false;}finally{if (fs != null){fs.Close();fs.Dispose();}if (zipStream != null){zipStream.Close();zipStream.Dispose();}if (ent != null){ent = null;}GC.Collect();GC.Collect(1);}return result;}#endregion#region 搜索引擎自動推送/// <summary>/// 搜索引擎鏈接推送/// </summary>/// <param name="urls"></param>/// <returns></returns>public static string PostUrl(string[] urls){try{string formUrl = "http://data.zz.baidu.com/urls?site=www.yealuo.com&token=nvLhHxq4HKwgKoCQ";string formData = "";foreach (string url in urls){formData += url + "\n";}byte[] postData = System.Text.Encoding.UTF8.GetBytes(formData);// 設置提交的相關參數 System.Net.HttpWebRequest request = System.Net.WebRequest.Create(formUrl) as System.Net.HttpWebRequest;System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;request.Method = "POST";request.KeepAlive = false;request.AllowAutoRedirect = true;request.ContentType = "text/plain";request.UserAgent = "curl/7.12.1";request.ContentLength = postData.Length;// 提交請求數據 System.IO.Stream outputStream = request.GetRequestStream();outputStream.Write(postData, 0, postData.Length);outputStream.Close();System.Net.HttpWebResponse response;System.IO.Stream responseStream;System.IO.StreamReader reader;string srcString;response = request.GetResponse() as System.Net.HttpWebResponse;responseStream = response.GetResponseStream();reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("UTF-8"));srcString = reader.ReadToEnd();string result = srcString; //返回值賦值reader.Close();return result;}catch (Exception ex){return ex.Message;}}#endregion} }
同樣的步驟,首先我們創建一個名為AttachmentMangeController的控制器、Index.cshtml視圖,以及業務類Com_AttachmentBll.cs:
(1)AttachmentMangeController.cs
using Bobo.Utilities; using IA.Business; using IA.Business.SystemBusiness; using IA.Entity; using IA.WebApp.SystemExtension; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using System.Xml;namespace IA.WebApp.Areas.BackstageModule.Controllers {/// <summary>/// 素材管理控制器/// </summary>[LoginAuthorize("~/BackstageModule/Login/Index")]public class AttachmentMangeController : PublicController<Com_Attachment>{//// GET: /BackstageModule/AttachmentMange//// <summary>/// 獲取分頁數據/// </summary>/// <param name="ArticleTitle"></param>/// <param name="jgp"></param>/// <returns></returns>public ActionResult GetTable(string FileTitle, JqGridParam jgp){FileTitle = FileTitle.Replace(" ", "");Com_AttachmentBll bll = new Com_AttachmentBll();DataTable model = bll.GetTablePage(FileTitle, ref jgp);//構建分頁數據var JsonData = new{success = true,pageData = jgp,message = "",data = model};return Content(JsonData.ToJson());}/// <summary>/// 添加編輯 /// </summary>/// <param name="entity"></param>/// <param name="KeyValue"></param>/// <returns></returns>public ActionResult SubmitFormData(Com_Attachment entity, string KeyValue){HttpPostedFileBase FileCover = Request.Files["FileCover"];HttpPostedFileBase FileUrl = Request.Files["FileUrl"];Com_AttachmentBll bll = new Com_AttachmentBll();try{int IsOk = 0;string Message = KeyValue == "" ? "新增成功。" : "編輯成功。";#region 附件處理bool FileHasCover = FileCover != null && FileCover.ContentLength > 0;bool FileHasUrl = FileUrl != null && FileUrl.ContentLength > 0;List<string> fileType = ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageType").ToLower().Split('|').ToList();string PicName = "";string FileUrName = "";if (FileHasCover){PicName = Path.GetFileName(FileCover.FileName);}if (FileHasUrl){FileUrName = Path.GetFileName(FileUrl.FileName);}if ((FileHasCover && !fileType.Contains(Path.GetExtension(PicName).ToLower()))){return Content(new JsonMessage { Code = "-1", Success = false, Message = "封面只能上傳" + ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageType").ToLower() + "類型的文件!" }.ToString());}var ssssl = FileCover.ContentLength;var ssss = CommonHelper.GetInt(SizeHelper.CountSizeNum(FileCover.ContentLength));if (FileHasCover && CommonHelper.GetInt(SizeHelper.CountSizeNum(FileCover.ContentLength)) > CommonHelper.GetInt(ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageSize"))){return Content(new JsonMessage { Code = "-1", Success = false, Message = "文件大小不能超過" + ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageSize") + "M!" }.ToString());}string strLower = Path.GetExtension(FileUrName).ToLower();if (FileHasUrl && (strLower != ".zip" && strLower != ".ZIP")){return Content(new JsonMessage { Code = "-1", Success = false, Message = "附件只能上傳ZIP類型的文件!" }.ToString());}if (FileHasUrl && CommonHelper.GetInt(SizeHelper.CountSizeNum(FileUrl.ContentLength)) > CommonHelper.GetInt(ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "BigSize"))){return Content(new JsonMessage { Code = "-1", Success = false, Message = "文件大小不能超過" + ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "BigSize") + "M!" }.ToString());}string AllPath = "";//ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "AllFilePath");string PicPath = "/Resource/Journal/FileCover/";string PicMinPath = "/Resource/Journal/FileMinCover/";DirFileHelper.CreateDirectory(Server.MapPath(AllPath + PicPath));DirFileHelper.CreateDirectory(Server.MapPath(AllPath + PicMinPath));//上傳FileCoverif (FileHasCover){string fileName = CommonHelper.GetGuidNotLine() + Path.GetExtension(PicName).ToLower();FileCover.SaveAs(Server.MapPath(AllPath + PicPath + fileName));entity.FileCover = PicPath + fileName;Image titleImg = Image.FromStream(FileCover.InputStream);PictureHelp.MakeThumbnail(titleImg,Server.MapPath(AllPath + PicMinPath) + fileName, 260, 0, "W");entity.FileMinCover = PicMinPath + fileName;}//上傳FileUrlstring FileUrlPath = "/Resource/Journal/FileUrl/";string guid = CommonHelper.GetGuid();DirFileHelper.CreateDirectory(Server.MapPath(AllPath + FileUrlPath + guid));if (FileHasUrl){string fileName = CommonHelper.GetGuidNotLine() + Path.GetFileName(FileUrl.FileName);FileUrl.SaveAs(Server.MapPath(AllPath + FileUrlPath + fileName));entity.FileUrl = FileUrlPath + fileName;if (entity.FileType == "FLASH" || entity.FileType == "PIC" || entity.FileType == "SYS"){entity.FileIndexUrl = "";}else{entity.FileIndexUrl = AllPath + FileUrlPath + guid + "/Index.html";BaseCommon.UnZip(Server.MapPath(AllPath + FileUrlPath + fileName), Server.MapPath(AllPath + FileUrlPath + guid), null);//壓縮包解壓}}#endregionif (!string.IsNullOrEmpty(KeyValue)){Com_Attachment Oldentity = bll.Factory.FindEntity(KeyValue);//獲取沒更新之前實體對象if (FileHasCover){ //修改的時候判斷是否有新上傳圖,有就刪除原圖片if (!StringHelper.IsNullOrEmpty(Oldentity.FileCover)){string path = Server.MapPath(Oldentity.FileCover);string path1 = Server.MapPath(Oldentity.FileMinCover);if (System.IO.File.Exists(path)){System.IO.File.Delete(path);}if (System.IO.File.Exists(path1)){System.IO.File.Delete(path1);}}}if (FileHasUrl){ //修改的時候判斷是否有新上文件,有就刪除原文件if (!StringHelper.IsNullOrEmpty(Oldentity.FileUrl)){string path = Server.MapPath(Oldentity.FileUrl);if (System.IO.File.Exists(path)){System.IO.File.Delete(path);}}if (!StringHelper.IsNullOrEmpty(Oldentity.FileIndexUrl)){string path = Path.GetDirectoryName(Server.MapPath(Oldentity.FileIndexUrl));if (Directory.Exists(path)){Directory.Delete(path, true);//刪除文件夾及子文件}}}entity.Modify(KeyValue);IsOk = bll.Factory.Update(entity);this.WriteLog(IsOk, entity, Oldentity, KeyValue, Message);}else{entity.Create();IsOk = bll.Factory.Insert(entity);if (IsOk > 0){KeyValue = entity.FileID;SetWebMapFile();BaseCommon.PostUrl(new string[] { KeyValue });}this.WriteLog(IsOk, entity, null, KeyValue, Message);}if (IsOk < 1){Message = "操作失敗";}new Base_DataDictionaryDetailBll().SubContentKey(entity.ContentKey);return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());}catch (Exception ex){this.WriteLog(-1, entity, null, KeyValue, "操作失敗:" + ex.Message);return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失敗:" + ex.Message }.ToString());}}/// <summary>/// 制造站長地圖文檔/// </summary>/// <returns></returns>public int SetWebMapFile(){try{//創建XmlDocument對象XmlDocument xmlDoc = new XmlDocument();//XML的聲明<?xml version="1.0" encoding="gb2312"?> XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);//追加xmldecl位置xmlDoc.AppendChild(xmlSM);//添加一個名為Gen的根節點XmlElement xml = xmlDoc.CreateElement("", "urlset", "");//追加Gen的根節點位置 xmlDoc.AppendChild(xml);//添加另一個節點,與Gen所匹配,查找<Gen>XmlNode urlset = xmlDoc.SelectSingleNode("urlset");Com_AttachmentBll bll = new Com_AttachmentBll();List<Com_Attachment> alist = bll.GetAttachmentList(null, null, null);foreach (var item in alist){XmlElement url = xmlDoc.CreateElement("url");XmlElement loc = xmlDoc.CreateElement("loc");//必填,定義某一個鏈接的入口,每一條數據必須要用<url>和</url>來標示//必填,URL長度限制在256字節內XmlElement lastmod = xmlDoc.CreateElement("lastmod");//更新時間標簽,非必填,用來表示最后更新時間XmlElement changefreq = xmlDoc.CreateElement("changefreq");//更新頻率標簽,非必填,用來告知引擎頁面的更新頻率XmlElement priority = xmlDoc.CreateElement("priority");//優先權標簽,優先權值0.0-1.0,用來告知引擎該條url的優先級string ul = "http://www.yealuo.com/Home/Detail";loc.InnerText = ul + "?" + item.FileID;lastmod.InnerText = DateTime.Now.ToString("yyy-MM-dd");changefreq.InnerText = "daily";priority.InnerText = "0.8";url.AppendChild(loc);url.AppendChild(lastmod);url.AppendChild(changefreq);url.AppendChild(priority);urlset.AppendChild(url);}DirFileHelper.CreateDirectory(Server.MapPath("~/Resource/360Map/"));xmlDoc.Save(Server.MapPath("~/Resource/360Map/Sitemap.xml"));return 1;}catch (Exception ex){return 0;}}/// <summary>/// 假刪方法(會刊)/// </summary>/// <param name="KeyValue"></param>/// <returns></returns>public ActionResult DeleteOther(string KeyValue){Com_AttachmentBll bll = new Com_AttachmentBll();try{int IsOk = 1;string Message = "刪除成功";if (!string.IsNullOrEmpty(KeyValue)){string[] array = KeyValue.Split(',');foreach (var item in array){Com_Attachment Oldentity = bll.Factory.FindEntity(item);//獲取沒更新之前實體對象Oldentity.DeleteMark = 1;Oldentity.Modify(item);IsOk = bll.Factory.Update(Oldentity);this.WriteLog(IsOk, Oldentity, Oldentity, item, Message);}}else{Message = "刪除失敗";IsOk = 1;}return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());}catch (Exception ex){this.WriteLog(-1, null, null, KeyValue, "操作失敗:" + ex.Message);return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失敗:" + ex.Message }.ToString());}}/// <summary>/// 獲取關鍵字/// </summary>/// <param name="title"></param>/// <returns></returns>public ActionResult GetContentKey(string title){Base_DataDictionaryDetailBll bll = new Base_DataDictionaryDetailBll();List<Base_DataDictionaryDetail> dlist = bll.GetDataDictionaryList(title, "ContentKey");return Content(dlist.ToJson());}} }
(2)Index.cshtml
@{ViewBag.Title = "素材管理";Layout = "~/Views/Shared/_LayoutMange.cshtml"; } <style>html {background-color: #f3f4f4;}.w_header .header-nav .nav-item li a.wzgl {border-bottom: 2px solid #2D81E0;background-color: #E8F4FF;color: #2D81E0;font-weight: bold;}.ContentKeyBox {padding-left: 85px;padding-top: 15px;line-height: 25px;}.ContentKeyBox a {margin: 5px;color: #666;display: inline-block;cursor: pointer;}.ContentKeyBox a:hover, .ContentKeyBox a.on {background-color: #0b234e;color: #fff;}.w_center .center-nav-item a.scgl {color: #156cd1;} </style> <div class="w_center clear mAuto">@Html.Partial("_PartialNav")<div class="center-main font-yahei R"><div class="center-main-nav"><a href="javascript:;" class="center-main-tag action" style="border-left:0 none;">素材編輯</a></div><div class="center-main-box" style="margin-top:0;"><div class="toolbarBox clear"><div id="searchForm" class="L searchForm"><span class="seachTit">素材標題:</span><input type="text" id="FileTitle" name="FileTitle" class="seachText" value="" /><a id="searchBtn" class="searchBtn" href="javascript:;" title="搜索"></a></div><div class="toolbar R"><input type="button" value="新增素材" class="addBtn greenBtn" οnclick="AddEditBtn(0,$(this))" /></div></div><ul class="list-ui clear" id="list-ui"></ul><div id="listPage" class="m_pageBar com_pageBar" style="padding:0 30px;"></div></div></div> </div>@*分頁數據模版*@ <script id="tempBody" type="text/template">{#each data as item}<li class="list-item"><div class="img-box"><img src="!{item.FileMinCover}" width="135" height="185" /><div class="list-mask"><a href="javascript:;" οnclick="AddEditBtn(1,$(this))" data-id="!{item.FileID}" class="list-btn list-edit L"><img src="/Content/Images/slice/edit.png" /> <span>編輯</span></a><a href="javascript:;" οnclick="delBtn($(this))" class="list-btn list-close R" data-id="!{item.FileID}"><img src="/Content/Images/slice/close.png" /> <span>刪除</span></a><a href="!{item.FileIndexUrl}" target="_blank" class="list-btn list-show L"><img src="/Content/Images/slice/show.png" /> <span>預覽</span></a></div></div><div class="list-title" title="!{item.FileTitle}">!{subString(item.FileTitle, 15)}</div></li>{#/each} </script>@*隱藏彈窗模版*@ <script id="ReplyEdit" type="text/template"><div style="margin:20px 20px;"><form id="form1" action="/BackstageModule/AttachmentMange/SubmitFormData" method="post" enctype="multipart/form-data" style="margin: 1px"><input type="hidden" id="KeyValue" name="KeyValue" /><table class="layer-table-form"><tr><td><span class="layer-form-tit">標題:</span><input type="text" name="FileTitle" class="layer-form-txt" id="FileTitle" datacol="yes" err="標題" checkexpession="NotNull" /></td></tr><tr><td><span class="layer-form-tit">金幣:</span><input type="text" name="Integral" class="layer-form-txt" id="Integral" datacol="yes" err="金幣" checkexpession="NumOrNull" /></td></tr><tr><td><span class="layer-form-tit">類型:</span><select name="FileType" class="layer-form-select" id="FileType" datacol="yes" err="類型" checkexpession="NotNull"><option value="">==請選擇==</option><option value="WEB">網站模板</option><option value="WAP">手機端</option><option value="H5C3">HTML5 CSS3</option><option value="WJS">網頁特效</option><option value="FLASH">flash素材</option><option value="PIC">網頁素材</option><option value="SYS">網站源碼</option></select></td></tr><tr><td><div class="layer-form-tit L">封面:</div><input type="text" name="FileCoverSet" id="FileCoverSet" class="layer-form-txt url1 L" readonly="readonly" style="display:none;" placeholder="請上傳.JPG|.JPEG|.PNG|.GIF|.BMP格式的圖片" datacol="yes" err="封面" /><input type="text" name="FileCover" id="FileCover" class="layer-form-txt url2 L" readonly="readonly" placeholder="請上傳.JPG|.JPEG|.PNG|.GIF|.BMP格式的圖片" datacol="yes" err="封面" /><div class="FileBox L"><input class="file upFile" type="file" name="FileCover" value="" οnchange="SetFileVal($(this))" /></div></td></tr><tr><td><div class="layer-form-tit L">附件:</div><input type="text" name="FileUrlSet" id="FileUrlSet" class="layer-form-txt url1 L" readonly="readonly" style="display:none;" placeholder="請上傳.zip格式的文件" datacol="yes" err="附件" /><input type="text" name="FileUrl" id="FileUrl" class="layer-form-txt url2 L" readonly="readonly" placeholder="請上傳.PDF|.DOC|.DOCX格式的文件" datacol="yes" err="封面" /><div class="FileBox L"><input class="file upFile" type="file" name="FileUrl" value="" οnchange="SetFileVal($(this))" /></div></td></tr><tr><td style="height:auto;vertical-align:top;"><div><span class="layer-form-tit">關鍵字:</span><input style="background-color:#efefef;border:0 none;width:405px;" type="text" name="ContentKey" class="layer-form-txt" id="ContentKey" datacol="yes" err="關鍵字" checkexpession="NotNull" readonly="readonly" /></div><div><span class="layer-form-tit">輸入關鍵字:</span><input type="text" class="layer-form-txt" id="SetContentKey" /><a style="display:inline-block;" class="addBtn yellowBtn" οnclick="SetContentKey($('#SetContentKey').val()); $('#SetContentKey').val('')">加入</a></div><div class="ContentKeyBox"></div></td></tr><tr><td><span class="layer-form-tit">介紹:</span><textarea name="Remarks" class="layer-form-txt" style="height:70px;" id="Remarks" datacol="yes" err="介紹" checkexpession="NotNull"></textarea></td></tr></table></form></div> </script>@*隱藏下載彈窗模版*@ <script id="DownList" type="text/template"><div style="margin:20px 20px;"><input type="hidden" id="KeyValue" name="KeyValue" /><table class="layer-table-form DownList"></table></div> </script> @section scripts{<script type="text/javascript">var KeyValue = "";$(function () {juicer.register('formatDate', formatDate);juicer.register('subString', subString);TagNavSet();getPageData();searchEvent();//getPageData2();});//菜單切換function TagNavSet() {$(".center-main-tag").on("click", function () {if (!$(this).hasClass("action")) {$(this).addClass("action").siblings(".center-main-tag").removeClass("action");$(".center-main-box").hide();$(".center-main-box").eq($(this).index()).show();}})}//初始化分頁函數function getPageData() {var param = {rows: 10,url: "/BackstageModule/AttachmentMange/GetTable",sidx: "CreateDate",sord: "DESC",searchForm: "#searchForm",infoPanel: '#list-ui',barPanel: '#listPage',template: '#tempBody',callback: handleSuccess}Pager.init(param);}//查詢按鈕綁定事件function searchEvent() {$("#searchBtn").on("click", function () {getPageData();});}//添加編輯彈窗function AddEditBtn(num, elem) {var allVal = "";if (num > 0) {allVal = elem.attr("data-id");}layer.open({title: "添加/編輯",type: 1,skin: 'layui-layer-rim', //加上邊框area: ['650px', '600px'], //寬高content: $("#ReplyEdit").html(),btn: ['保存', '取消'], //只是為了演示yes: function () {AcceptClick();}});InitControl(allVal);GetContentKey("");}//保存按鈕function AcceptClick() {if (!CheckDataValid('#form1', true)) {return false;}//提交表單$("#form1").ajaxSubmit({dataType: "json",beforeSubmit: function () {layer.msg('正在提交信息,請稍后…', { icon: 16, shade: 0.2, time: 0 });},success: function (data) {if (data.Success) {layer.msg(data.Message, { icon: data.Code, time: 1000 }, function () {layer.closeAll();getPageData();});}else {layer.alert(data.Message, { icon: data.Code });}}});}//刪除function delBtn(elem) {var allVal = elem.attr("data-id");layer.confirm("是否刪除這" + allVal.split(",").length + "條數據?", { icon: 0 }, function () {AjaxJson("/BackstageModule/AttachmentMange/DeleteOther", { KeyValue: allVal }, function (data) {layer.msg(data.Message, { icon: data.Code, time: 1000 }, function () {getPageData();});});});}//文件域選擇設置function SetFileVal(elem) {var part = elem.parents("td");if (!!elem.val()) {part.find(".url1").val(elem.val()).show().attr("checkexpession", "NotNull");part.find(".url2").hide().removeAttr("checkexpession");}else {part.find(".url1").show().attr("checkexpession", "NotNull");part.find(".url2").hide().removeAttr("checkexpession");}}//得到一個對象實體function InitControl(allVal) {AjaxJson("/BackstageModule/AttachmentMange/SetForm", { KeyValue: allVal }, function (data) {SetWebControls(data, "#form1");$("#KeyValue").val(data.FileID);$("#FileCover").attr("checkexpession", "NotNull");$("#FileUrl").attr("checkexpession", "NotNull");});}//分頁數據加載后綁定的函數function handleSuccess() {checkAll();}//全選(包括)function checkAll() {//全選按鈕$(".dataTable thead").find(".ckbAll").change(function () {var chkAll = $(this);var chkVal = chkAll.prop("checked");if (chkVal == "checked" || chkVal == true) {$(".dataTable tbody tr").each(function () {var chk = $(this).find(":checkbox");chk.prop("checked", "checked");});}else {$(".dataTable tbody tr").each(function () {var chk = $(this).find(":checkbox");chk.removeAttr("checked");});}});}//關鍵字設置function SetContentKey(val) {var _thisVal = $("#ContentKey").val();if (_thisVal.indexOf(val) > 0) {layer.msg("已包含該關鍵字", { icon: "-1", time: 2000 });}else if (!!val) {(!_thisVal) ? $("#ContentKey").val(val) : $("#ContentKey").val(_thisVal + "," + val);}}//獲取關鍵字function GetContentKey(title) {$.post("/BackstageModule/AttachmentMange/GetContentKey", { title: title }, function (data) {var strHtml = "";for (var i = 0; i < data.length; i++) {strHtml += "<a οnclick=\"SetContentKey('" + data[i].DataDictionaryTitle + "');$(this).addClass('on');\">" + data[i].DataDictionaryTitle + "</a>";}$(".ContentKeyBox").html(strHtml);}, "json")}</script>}
(3)Com_AttachmentBll.css
using Bobo.DataAccess; using Bobo.Repository; using Bobo.Utilities; using IA.Entity; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web;namespace IA.Business {// <summary> /// 素材表 /// <author> /// <name>YHB</name> /// <date>2018.10.18</date> /// </author> /// </summary> public class Com_AttachmentBll : RepositoryFactory<Com_Attachment>{/// <summary>/// 獲取附件數據/// </summary>/// <param name="ArticleTitle"></param>/// <param name="jgp"></param>/// <returns></returns>public DataTable GetTablePage(string FileTitle, ref JqGridParam jgp){StringBuilder whereSql = new StringBuilder();List<DbParameter> param = new List<DbParameter>();whereSql.Append(@" AND DeleteMark<>1");if (!StringHelper.IsNullOrEmpty(FileTitle)){whereSql.Append(@" AND FileTitle LIKE @FileTitle");param.Add(DbFactory.CreateDbParameter("@FileTitle", '%' + FileTitle + '%'));}return Factory.FindTablePage(whereSql.ToString(), param.ToArray(), ref jgp);}/// <summary>/// 獲取附件列表/// </summary>/// <param name="DataID"></param>/// <returns></returns>public List<Com_Attachment> GetAttachmentList(string DataID, int? topNum, string ByType){StringBuilder Sql = new StringBuilder();List<DbParameter> param = new List<DbParameter>();string where = "*";if (!StringHelper.IsNullOrEmpty(topNum) && topNum > 0){where = "TOP(" + topNum + ") *";}Sql.Append(@"SELECT " + where + " FROM Com_Attachment WHERE DeleteMark<>1");if (!StringHelper.IsNullOrEmpty(DataID)){Sql.Append(@" AND DataID=@DataID");param.Add(DbFactory.CreateDbParameter("@DataID", DataID));}if (!StringHelper.IsNullOrEmpty(ByType)){Sql.Append(@" ORDER BY " + ByType + " DESC");}return Factory.FindListBySql(Sql.ToString(), param.ToArray());}} }
(4)效果預覽: