public ActionResult Create([Bind(Include = "ID,Title,Content")] Post post,string Tags) { if (ModelState.IsValid) { post.CreateTime = DateTime.UtcNow; post.LastModified = DateTime.UtcNow; post.Urlslug = new Regex("[^a-zA-Z0-9\u4e00-\u9fa5]+").Replace(post.Title, "-"); //post.Tags.Add() foreach (var t in Tags.Split(',')) { var s = t.Trim(); Tag curTag; if (!_repo.getTags().Any(p => p.name == s)) { curTag = new Tag { name = s }; db.Tags.Add(curTag); } else { curTag = _repo.getTags().Where(x => x.name == s).Single(); } if (curTag.posts == null) { curTag.posts = new List<Post>(); } if (post.Tags == null) { post.Tags = new List<Tag>(); } curTag.posts.Add(post); post.Tags.Add(curTag); } db.Posts.Add(post); db.SaveChanges(); return RedirectToAction("Index"); } return View(post); }
public ActionResult Edit([Bind(Include = "ID,Title,Content,CreateTime")] Post post,string Tags) { if (ModelState.IsValid) { Post prev = db.Posts.Find(post.ID); post.CreateTime = post.CreateTime; post.LastModified = DateTime.UtcNow; post.Urlslug = new Regex("[^a-zA-Z0-9\u4e00-\u9fa5]+").Replace(post.Title, "-"); //remove original tags from database foreach (var t in prev.Tags.ToList()) { if (t.posts.Count == 1) { db.Tags.Remove(t); } else if (t.posts.Count > 1) { db.Tags.Find(t.name).posts.Remove(prev); } } db.Posts.Remove(prev); db.SaveChanges(); foreach (var t in Tags.Split(',')) { var s = t.Trim(); Tag curTag; if (!_repo.getTags().Any(p => p.name == s)) { curTag = new Tag { name = s }; db.Tags.Add(curTag); } else { curTag = _repo.getTags().Where(x => x.name == s).Single(); db.Entry(curTag).State = EntityState.Modified; } if (curTag.posts == null) { curTag.posts = new List<Post>(); } if (post.Tags == null) { post.Tags = new List<Tag>(); } curTag.posts.Add(post); post.Tags.Add(curTag); } db.Posts.Add(post); db.SaveChanges(); return RedirectToAction("Index"); } return View(post); }