public ActionResult Edit(ArticleManageEditViewModel model) { if (ModelState.IsValid) { var tagsList = ArticleHandler.ConvertTagsStringToList(model.ArticleTagsForArticle); //check tags and save foreach(var tagName in tagsList) { if (!db.ArticleTags.Any(t => t.Name ==tagName)) { var articleTag = new ArticleTag { Name = tagName }; db.ArticleTags.Add(articleTag); db.SaveChanges(); } } string newCoverImgUrl; if (model.CoverImg != null) { var uploadedFile = new UploadedFile(model.CoverImg); var coverImgName = uploadedFile.SaveAsWithGuid(Server.MapPath("~/ImgRepository/ArticleImgs/" + model.Id)); var pathRel = Url.Content("~/ImgRepository/ArticleImgs/" + model.Id + "/" + coverImgName); newCoverImgUrl = pathRel; } else { newCoverImgUrl = db.Articles.Find(model.Id).CoverImgUrl; } var article = db.Articles.Find(model.Id); article.Id = model.Id; article.Title = model.Title; article.CoverImgUrl = newCoverImgUrl; article.ShortDescription = model.ShortDescription; article.Description = model.Description; article.Content = model.Content; article.Meta = model.Meta; article.UrlSlug = model.UrlSlug; article.IsPublished = model.IsPublished; article.PostTime = model.PostTime; article.ModifyTime = model.ModifyTime; article.CategoryId = db.ArticleCategories.Find(model.ArticleCategoryForArticle).Id; article.Category = db.ArticleCategories.Find(model.ArticleCategoryForArticle); article.Tags.Clear(); article.Tags = db.ArticleTags.Where(t => tagsList.Contains(t.Name)).ToList(); article.Dialogs.Clear(); db.ArticleDialogs.Where(a => a.ArticleId == article.Id).ToList().ForEach(ad => db.ArticleDialogs.Remove(ad)); for (int i = 0; i < model.ArticleDialogs.Count; i++) { model.ArticleDialogs[i].SequenceNumber = i + 1; } article.Dialogs = model.ArticleDialogs; db.Entry(article).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(model); }
// GET: ArticleManage/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Article article = db.Articles.Find(id); if (article == null) { return HttpNotFound(); } var vm = new ArticleManageEditViewModel { Id = article.Id, Title = article.Title, CoverImgUrl=article.CoverImgUrl, ShortDescription = article.ShortDescription, Description = article.Description, Content=article.Content, Meta = article.Meta, UrlSlug = article.UrlSlug, IsPublished = article.IsPublished, PostTime = article.PostTime, ModifyTime = article.ModifyTime??DateTime.Now, ArticleCategoryForArticle = article.CategoryId, ArticleCategories = db.ArticleCategories.ToList(), Tags = article.Tags, ArticleDialogs=article.Dialogs.Count>0?article.Dialogs:new List<ArticleDialog> { new ArticleDialog() }, Characters=db.Characters.ToList() }; return View(vm); }