コード例 #1
0
        public ActionResult WriteComment(WriteCommentModel model, int postId)
        {
            using (var db = new BlogModels())
            {
                Post post;
                post = db.Posts.Include(p => p.Comments).Single(p => p.Id == postId);

                model.Post = post;
                using (var idb = new IdentityDbContext())
                {
                    var authors = post.Comments.Select(p => p.Author).ToList();
                    authors.Add(post.Author);
                    List <IdentityUser> allAuth = new List <IdentityUser>();
                    foreach (string author in authors)
                    {
                        var autor = idb.Users.FirstOrDefault(u => u.Id == author);
                        if (autor != null)
                        {
                            allAuth.Add(autor);
                        }
                    }

                    model.AllAuthors = allAuth.ToArray();
                }

                if (ModelState.IsValid)
                {
                    Comment newC = new Comment()
                    {
                        Author       = User.Identity.GetUserId(),
                        Body         = model.Body,
                        Likes        = 0,
                        Views        = 0,
                        CreationTime = DateTime.Now,
                    };
                    db.Entry(post).Entity.Comments.Add(newC);
                    db.SaveChanges();
                    return(RedirectToAction("Index", "Blog"));
                }

                ModelState.AddModelError("", "Заполните все поля!");
                return(View(model));
            }
        }