Example #1
0
        public JsonResult Create(int PostId /* ,String UserId*/)
        {
            int flag = 0;

            UserLikesPost userLikesPost = new UserLikesPost();

            userLikesPost.UserId = _userManager.GetUserId(User);/*UserId;*/
            userLikesPost.PostId = PostId;
            var u = _context.UserLikesPosts.FirstOrDefault(m => m.UserId == userLikesPost.UserId && m.PostId == userLikesPost.PostId && m.IsLiked == true);

            if (u == null)     //Like
            {
                var uu = _context.UserLikesPosts.FirstOrDefault(m => m.UserId == userLikesPost.UserId && m.PostId == userLikesPost.PostId);
                if (uu == null)     //first like
                {
                    userLikesPost.IsLiked = true;
                    _context.UserLikesPosts.Add(userLikesPost);
                }
                else     //was liked before
                {
                    uu.IsLiked = true;
                }
            }
            else     //Dislike
            {
                u.IsLiked = false;
            }
            _context.SaveChanges();
            //return RedirectToAction(nameof(Index));

            ViewData["PostId"] = new SelectList(_context.Posts, "Id", "Id", userLikesPost.PostId);
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", userLikesPost.UserId);
            //return View(userLikesPost);
            return(Json(""));
        }
        public async Task <IActionResult> Create([Bind("UserId,PostId,IsLiked")] UserLikesPost userLikesPost)
        {
            int flag = 0;

            if (ModelState.IsValid)
            {
                userLikesPost.UserId = _userManager.GetUserId(User);
                var u = await _context.UserLikesPosts.FirstOrDefaultAsync(m => m.UserId == userLikesPost.UserId && m.PostId == userLikesPost.PostId && m.IsLiked == true);

                if (u == null) //Like
                {
                    var uu = await _context.UserLikesPosts.FirstOrDefaultAsync(m => m.UserId == userLikesPost.UserId && m.PostId == userLikesPost.PostId);

                    if (uu == null) //first like
                    {
                        userLikesPost.IsLiked = true;
                        _context.Add(userLikesPost);
                    }
                    else //was liked before
                    {
                        uu.IsLiked = true;
                    }
                }
                else //Dislike
                {
                    u.IsLiked = false;
                }
                await _context.SaveChangesAsync();

                //return RedirectToAction(nameof(Index));
            }
            ViewData["PostId"] = new SelectList(_context.Posts, "Id", "Id", userLikesPost.PostId);
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", userLikesPost.UserId);
            //return View(userLikesPost);
            return(RedirectToAction("Index", "Home", new { flag }));
        }