FYJ.Blogs开发系列(四)-后台文章Controller
FYJ.Blogs开发系列(五)-前台基页Controller
FYJ.Blogs开发系列(六)-前台主页Controller
FYJ.Blogs开发系列(七)-前台文章Controller
using Blogs.Common; using Blogs.Entity; using Blogs.UI.Admin.Filters; using Blogs.ViewModel; using Blogs.ViewModel.MyBlog; using FYJ.Pager; using FYJ.Common; using Microsoft.Practices.Unity; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; namespace Blogs.UI.Admin.Areas.MyBlog.Controllers { [LogFilter] [ExceptionFilter] [AuthenFilter] public class ArticleController : Controller { public ActionResult Index() { int blogID = UserInfo.BlogID; string userID = UserInfo.UserID; var blogs = BlogDal.GetEntities().Where(c => c.userID == userID).OrderByDescending(c => c.blogOrder).Select(c => new { c.blogTitle, c.blogID }).ToList(); //下面的ViewData["BlogSelect"] 中的BlogSelect 不能与 @Html.DropDownList("ddlBlogSelect", ViewData["BlogSelect"] as IEnumerable<SelectListItem>) ddlBlogSelect 一样 //但是用DataTable.AsDataView() 就可以? 不然默认值选不中 ViewData["BlogSelect"] = new SelectList(blogs, "blogID", "blogTitle", blogID); var categorys = categoryDal.GetcategorysTreeTable(blogID + "").AsDataView(); var topics = TopicDal.GetEntities().Where(c => c.blogID == blogID); ViewData["categorySelect"] = new SelectList(categorys, "categoryID", "categoryDisplay"); ViewData["TopicSelect"] = new SelectList(topics, "topicID", "topicDisplay"); var siteCategorys = SiteCategoryDal.GetcategorysTreeTable().AsDataView(); ViewData["siteCategorySelect"] = new SelectList(siteCategorys, "categoryID", "categoryDisplay"); return View(); } #region 依赖属性 [Dependency] public Blogs.IDAL.IBlog BlogDal { get; set; } [Dependency] public Blogs.IDAL.ICategory categoryDal { get; set; } [Dependency] public Blogs.IDAL.IArticle ArticleDal { get; set; } [Dependency] public Blogs.IDAL.IArticleView ArticleViewDal { get; set; } [Dependency] public Blogs.IDAL.ITopic TopicDal { get; set; } [Dependency] public Blogs.IDAL.ITag TagDal { get; set; } [Dependency] public Blogs.IDAL.ITheme ThemeDal { get; set; } [Dependency] public Blogs.IDAL.ISiteCategory SiteCategoryDal { get; set; } [Dependency] public Blogs.IDAL.IComment CommentDal { get; set; } [Dependency] public Blogs.IDAL.IFileRelation FileRelationDal { get; set; } #endregion [LogFilter("查询文章", "查询了文章列表", true)] public JsonResult GetList(GridPager pager, string queryStr) { int blogID = UserInfo.BlogID; pager.CurrentPage = Convert.ToInt32(Request["page"]); pager.PageSize = Convert.ToInt32(Request["rows"]); pager.OrderColumn = Request["sort"]; pager.Order = Request["order"]; List<Func<blog_view_article, bool>> wheres = new List<Func<blog_view_article, bool>>(); if (!String.IsNullOrWhiteSpace(Request["ddlBlogSelect"])) { int sblogID = Int32.Parse(Request["ddlBlogSelect"]); wheres.Add(c => c.blogID == sblogID); } if (!String.IsNullOrWhiteSpace(Request["ddlsiteCategorySelect"])) { int id = Int32.Parse(Request["ddlsiteCategorySelect"]); wheres.Add(c => c.siteCategoryID == id); } if (!String.IsNullOrWhiteSpace(Request["ddlcategorySelect"])) { int id = Int32.Parse(Request["ddlcategorySelect"]); wheres.Add(c => c.categoryID == id); } if (!String.IsNullOrWhiteSpace(Request["ddlTopicSelect"])) { int id = Int32.Parse(Request["ddlTopicSelect"]); wheres.Add(c => c.topicID == id); } if (!String.IsNullOrWhiteSpace(Request["ddlarticleIsOriginalSelect"])) { bool b = (Int32.Parse(Request["ddlarticleIsOriginalSelect"]) == 1); wheres.Add(c => c.articleIsOriginal == b); } if (!String.IsNullOrWhiteSpace(Request["StartDate"])) { wheres.Add(c => c.articleDatetime.Date >= Convert.ToDateTime(Request["StartDate"]).Date); } if (!String.IsNullOrWhiteSpace(Request["EndDate"])) { wheres.Add(c => c.articleDatetime.Date <= Convert.ToDateTime(Request["EndDate"]).Date); } if (!String.IsNullOrWhiteSpace(Request["articleTitle"])) { wheres.Add(c => c.articleTitle.ToLower().Contains(Request["articleTitle"].Trim().ToLower())); } IEnumerable<Blogs.Entity.blog_view_article> list = ArticleViewDal.GetList(ref pager, wheres.ToArray()); var json = new { total = pager.TotalRows, rows = (from r in list select new { ID = r.articleID, r.articleID, r.siteCategoryDisplay, r.categoryDisplay, r.topicDisplay, r.articleTitle, r.articlePic, r.articleIsPic, r.articleIsOriginal, r.articleIsDisabled, r.articleIsTop, r.articleClickTimes, r.articleCommentTimes, r.articleThemeDisplay, r.articlePostBy, r.themeDisplay, articleDatetime = r.articleDatetime.ToString("yyyy-MM-dd HH:mm:ss"), ADD_DATE = r.ADD_DATE.ToString("yyyy-MM-dd HH:mm:ss"), UPDATE_DATE = r.UPDATE_DATE.ToString("yyyy-MM-dd HH:mm:ss"), isDisableComment = CommentDal.isDisableComment(r.articleCommentLimit), isAllowAnonymousComment = CommentDal.isDisabledAnonymousComment(r.articleCommentLimit), isVerifyComment = CommentDal.isVerifyComment(r.articleCommentLimit) }).ToArray() }; return Json(json, JsonRequestBehavior.AllowGet); } public ActionResult GetCategoryJson() { string blogID = Request["blogID"]; var dt = categoryDal.GetcategorysTreeTable(blogID + ""); List<object> categorys = new List<object>(); categorys.Add(new { categoryID = "", categoryDisplay = "--请选择--" }); foreach (DataRow dr in dt.Rows) { categorys.Add(new { categoryID = Convert.ToInt32(dr["categoryID"]), categoryDisplay = dr["categoryDisplay"].ToString() }); } return Json(categorys, JsonRequestBehavior.AllowGet); } public ActionResult GetTopicJson() { int blogID = Convert.ToInt32(Request["blogID"]); var topics = TopicDal.GetEntities().Where(c => c.blogID == blogID).ToList(); List<object> list = new List<object>(); foreach (blog_tb_topic topic in topics) { list.Add(new { topicID = topic.topicID, topicDisplay = topic.topicDisplay }); } list.Insert(0, new { topicID = "", topicDisplay = "--请选择--" }); return Json(list, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult ChangeArticle(FormCollection collection) { string[] ids = Request["ids"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); int result = ArticleDal.ChangeArticle(ids, Request["blogID"], Request["categoryID"]); if (result > 0) { return Json(new { code = 1, message = "操作成功" }, JsonRequestBehavior.AllowGet); } return Json(new { code = -1, message = "操作成功" }, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult ChangeState(FormCollection collection) { if (collection["fieldName"] == "blogID") { int result = 0; string[] ids = Request["ids"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in ids) { result += ArticleDal.ChangeBlog(id, Request["blogID"]); } if (result > 0) { return Json(new { code = 1, message = "操作成功" }, JsonRequestBehavior.AllowGet); } } else { if (ArticleDal.Update(Request["ids"], Request["fieldName"], Request["state"]) > 0) { return Json(new { code = 1, message = "操作成功" }, JsonRequestBehavior.AllowGet); } } return Json(new { code = -1, message = "操作失败" }, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult TagString(FormCollection collection) { var v = TagDal.GetEntities().Where(c => c.blogID == Convert.ToInt32(Request["blogID"])); string tagString = ""; foreach (var item in v) { tagString += item.tagDisplay + ","; } tagString = tagString.TrimEnd(','); return Content(tagString); } [HttpPost] public ActionResult Attachment(FormCollection collection) { //IDictionary<string, string> dic = new Dictionary<string, string>(); //dic.Add("userID", "8dc2885cd7bb44aa9344557dbc0c1630"); //dic.Add("ak", "afbf3d192908477d9e24b3e351bc4ebe"); //dic.Add("action", "getFileUrl"); //dic.Add("objectTag", "attachment"); //dic.Add("objectID", Request["articID"]); //string par = ""; //string sign = FYJ.Common.HttpHelper.Sign(dic, "493d453149f943e0b515f068e2d029d6", out par, "sign"); //string url = "http://my.fyj.me/service/file.action?" + par + "&sign=" + sign; //string json = FYJ.Common.HttpHelper.DoGet(url); //DataTable dt = FYJ.Common.JsonHelper.JsonToDataTable(json); //if (dt != null && dt.Rows.Count > 0) //{ // foreach (DataRow dr in dt.Rows) // { // str += "<p><a href='" + dr["fileUrl"] + "' target='_blank'>" + dr["fileName"] + "</a></p>"; // } //} return Content(""); } public ActionResult Edit(string id) { if (id == null) { return null; } int objectID; blog_tb_article model = new blog_tb_article { blogID = UserInfo.BlogID, ADD_DATE = DateTime.Now, UPDATE_DATE = DateTime.Now, articleDatetime = DateTime.Now }; if ((!String.IsNullOrEmpty(id)) && id.ToString() != "0") { objectID = Convert.ToInt32(id); model = ArticleDal.GetEntities().Where(c => c.articleID == objectID).FirstOrDefault(); string tagString = ""; foreach (var item in model.blog_tb_tagArticle) { tagString += item.blog_tb_tag.tagDisplay + ","; } tagString = tagString.TrimEnd(','); ViewData["tagString"] = tagString; model.UPDATE_DATE = DateTime.Now; blog_tb_article_content contentModel = model.blog_tb_article_content.FirstOrDefault(); //加载临时正文 string tempContent = ArticleDal.ReadTempContent(id); if (!String.IsNullOrEmpty(tempContent)) { contentModel.articleContent = tempContent; } ViewData["content"] = contentModel; } else { string lastArticleID = ArticleDal.LoadLastArticleID(); if (!String.IsNullOrEmpty(lastArticleID)) { objectID = Convert.ToInt32(lastArticleID); string tempContent = ArticleDal.ReadTempContent(lastArticleID); blog_tb_article_content contentModel = new blog_tb_article_content(); contentModel.articleContent = tempContent; contentModel.UPDATE_DATE = DateTime.Now; ViewData["content"] = contentModel; } else { objectID = Convert.ToInt32(ArticleDal.NewID()); } } int blogID = model.blogID; string userID = UserInfo.UserID; var siteCategorys = SiteCategoryDal.GetcategorysTreeTable().AsDataView(); var categorys = categoryDal.GetcategorysTreeTable(blogID + "").AsDataView(); var topics = TopicDal.GetEntities().Where(c => c.blogID == blogID); var tags = TagDal.GetEntities().Where(c => c.blogID == blogID); var blogs = BlogDal.GetEntities().Where(c => c.userID == userID); ViewData["siteCategorySelect"] = new SelectList(siteCategorys, "categoryID", "categoryDisplay"); ViewData["categorySelect"] = new SelectList(categorys, "categoryID", "categoryDisplay"); ViewData["TopicSelect"] = new SelectList(topics, "topicID", "topicDisplay"); ViewData["TagSelect"] = new SelectList(tags, "tagID", "tagDisplay"); ViewData["blogSelect"] = new SelectList(blogs, "blogID", "blogTitle"); List<blog_tb_theme> list = ThemeDal.GetEntities().ToList(); list.Insert(0, new blog_tb_theme { themeID = "", themeDisplay = "--请选择--" }); ViewData["Theme"] = new SelectList(list, "themeID", "themeDisplay", ""); if (tags.Count() > 0) { } ViewData["objectID"] = objectID; //两个上传控件的ID ViewData["uploadID1"] = GetUploadModel1(objectID + ""); ViewData["uploadID2"] = GetUploadModel2(objectID + ""); Blogs.ViewModel.MyBlog.Article m = model.CloneProperties<Blogs.ViewModel.MyBlog.Article>(); m.IsDisableComment = CommentDal.isDisableComment(model.articleCommentLimit); m.IsDisabledAnonymouComment = CommentDal.isDisabledAnonymousComment(model.articleCommentLimit); m.IsVerifyComment = CommentDal.isVerifyComment(model.articleCommentLimit); return View(m); } private UploadModel GetUploadModel1(string objectID) { UploadModel model = new UploadModel { ID = Guid.NewGuid().ToString("N"), AllowMulti = false, IsImage = true, ObjectType = "blog", ObjectTag = "mainPic", UploadDir = "pic", ThumHeight = 360, ThumWidth = 480, ThumPassSizeKB = 1024, ObjectID = objectID, IsSinglePic = true ,FileTag="blog"}; IEnumerable<blog_tb_fileRelation> relations = FileRelationDal.GetEntities().Where(c => c.objectID == objectID && c.objectTag == "mainPic").ToList(); if (relations != null) { List<FileLink> links = new List<FileLink>(); foreach (blog_tb_fileRelation relation in relations) { blog_tb_file file = relation.blog_tb_file; string fileName = file.fileName; if (String.IsNullOrEmpty(fileName)) { fileName = Path.GetFileName(file.fileUrl); } links.Add(new FileLink(relation.relationID,file.fileID, fileName, file.fileUrl)); } model.Files = links; //首张图片 model.FirstImage = links.FirstOrDefault(); } return model; } private UploadModel GetUploadModel2(string objectID) { UploadModel model = new UploadModel { ID = Guid.NewGuid().ToString("N"), UploadDir = "file", AllowMulti = true, ObjectType = "blog", ObjectTag = "attachment", IsImage = false, ObjectID = objectID,FileTag="blog" }; IEnumerable<blog_tb_fileRelation> relations = FileRelationDal.GetEntities().Where(c => c.objectID == objectID && c.objectTag == "attachment").ToList(); if (relations != null) { List<FileLink> links = new List<FileLink>(); foreach (blog_tb_fileRelation relation in relations) { blog_tb_file file = relation.blog_tb_file; string fileName = file.fileName; int size = (file.fileSize == null ? 0 : (int)file.fileSize.Value); if (String.IsNullOrEmpty(fileName)) { fileName = Path.GetFileName(file.fileUrl); } links.Add(new FileLink(relation.relationID,file.fileID, fileName, file.fileUrl) { Size = size }); } model.Files = links; } return model; } private void MyUpdateModel(object obj, FormCollection collection) { string[] keys = collection.AllKeys; PropertyInfo[] pis = obj.GetType().GetProperties(); foreach (PropertyInfo pi in pis) { string name = pi.Name; if (keys.Contains(name)) { string value = collection[name]; if (value == "true,false") { pi.SetValue(obj, true); } else { pi.SetValue(obj, value.ConvertValue(pi.PropertyType)); } } } } [HttpPost] public JsonResult Edit(string id, FormCollection collection) { int articleID = Convert.ToInt32(Request["objectID"]); string userID = UserInfo.UserID; Article m = new Article(); MyUpdateModel(m, collection); CommentLimit articleCommentLimit = 0; if (m.IsDisableComment) { articleCommentLimit |= CommentLimit.禁止回复; } if (m.IsVerifyComment) { articleCommentLimit |= CommentLimit.需要审核; } if (m.IsDisabledAnonymouComment) { articleCommentLimit |= CommentLimit.禁止匿名用户回复; } AttachmentLimit attachmentLimit = 0; if (!String.IsNullOrEmpty(Request["chkAttachmentLimit"])) { if (Request["chkAttachmentLimit"].Contains("1")) { attachmentLimit |= AttachmentLimit.禁止未登录用户下载; } if (Request["chkAttachmentLimit"].Contains("2")) { attachmentLimit |= AttachmentLimit.禁止未回复用户下载; } if (Request["chkAttachmentLimit"].Contains("3")) { attachmentLimit |= AttachmentLimit.禁止下载; } } blog_tb_article model = new blog_tb_article(); if (String.IsNullOrEmpty(id) || id == "0") //新增 { //UpdateModel(model); MyUpdateModel(model, collection); model.articleID = articleID; model.ADD_DATE = DateTime.Now; model.UPDATE_DATE = DateTime.Now; Blogs.Entity.blog_tb_article_content contentModel = new blog_tb_article_content(); contentModel.UPDATE_DATE = DateTime.Now; MyUpdateModel(contentModel, collection); contentModel.contentID = Guid.NewGuid().ToString("N"); model.blog_tb_article_content = new blog_tb_article_content[] { contentModel }; //设置图片 SetPic(model); model.articleCommentLimit = (int)articleCommentLimit; model.articleAttachmentLimit = (int)attachmentLimit; ArticleDal.InsertEntity(model); } else { model = ArticleDal.GetEntities().Where(c => c.articleID == articleID).FirstOrDefault(); model.articlePic = Request["fileUrlName_" + Request["uploadID1"]]; model.articleThumbPic = Request["thumUrlName_" + Request["uploadID1"]]; MyUpdateModel(model, collection); model.UPDATE_DATE = DateTime.Now; Blogs.Entity.blog_tb_article_content contentModel = model.blog_tb_article_content.FirstOrDefault(); MyUpdateModel(contentModel, collection); contentModel.UPDATE_DATE = DateTime.Now; //设置图片 SetPic(model); model.articleCommentLimit = (int)articleCommentLimit; model.articleAttachmentLimit = (int)attachmentLimit; ArticleDal.UpdateEntity(model); } //处理标签 必须后处理 因为之前还没有插入articleID if (!String.IsNullOrEmpty(Request["txt_tag"])) { TagDal.UpdateTag(Request["blogID"], articleID + "", Request["txt_tag"].TrimEnd(',')); } return Json(new { code = 1, message = "操作成功" }, JsonRequestBehavior.AllowGet); } private void SetPic(blog_tb_article model) { string fileUrl = Request["lastImageName_mainPic_" + model.articleID]; if (!String.IsNullOrEmpty(fileUrl)) { model.articlePic = fileUrl; //model.articleThumbPic = fileUrl; } } [HttpPost] public JsonResult Delete(FormCollection collection) { ArticleDal.DeleteEntity(collection["ids"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); return Json(new { code = 1, message = "删除成功" }, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult CreateCatelog(FormCollection collection) { ArticleDal.CreateCatelog(collection["ids"]); return Json(new { code = 1, message = "生成目录成功" }, JsonRequestBehavior.AllowGet); } public ActionResult View(int id) { var model = ArticleDal.GetEntities().Where(c => c.articleID == id).FirstOrDefault(); return View(model); } [HttpPost] public JsonResult SaveTempContent(FormCollection collection) { string articleID = Request["objectID"]; string articleContent = Request["articleContent"]; ArticleDal.SaveTempContent(articleID, articleContent); return Json(new { code = 1, message = DateTime.Now.ToString("HH:mm:ss") + "草稿保存成功" }, JsonRequestBehavior.AllowGet); } public ActionResult ueditorEdit(int id) { var model = ArticleDal.GetEntities().Where(c => c.articleID == id).FirstOrDefault(); blog_tb_article_content contentModel = model.blog_tb_article_content.FirstOrDefault(); //加载临时正文 string tempContent = ArticleDal.ReadTempContent(id + ""); if (!String.IsNullOrEmpty(tempContent)) { contentModel.articleContent = tempContent; } ViewData["content"] = contentModel; Blogs.ViewModel.MyBlog.Article m = model.CloneProperties<Blogs.ViewModel.MyBlog.Article>(); return View(m); } } }