示例#1
0
        public ActionResult AddComment(BlogViewModel model)
        {
            bool   isAdded = false;
            string error   = "";

            try
            {
                if (ModelState.IsValid)
                {
                    var posts   = GetPostsFromSession();
                    var comment = new Comment()
                    {
                        Name    = model.Comment.Name,
                        Email   = model.Comment.Email,
                        Date    = DateTime.UtcNow,
                        Message = model.Comment.Message
                    };
                    model.Comment.Date = DateTime.UtcNow.ToString("MMMM dd, yyyy HH:mm");
                    var comments = posts.Where(p => p.ID == model.Comment.BlogID).FirstOrDefault().Comments;
                    if (comments == null)
                    {
                        comments = new List <Comment>();
                    }
                    comments.Add(comment);
                    posts.Where(p => p.ID == model.Comment.BlogID).FirstOrDefault().Comments = comments;
                    isAdded = postsService.SaveAll(posts);
                    if (isAdded)
                    {
                        TempData["blogPosts"] = JsonConvert.SerializeObject(posts);
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message.ToString();
            }
            return(Json(new { IsAdded = isAdded, Comment = model.Comment, Exception = error }, JsonRequestBehavior.AllowGet));
        }