public async Task <ActionResult> FavoritePost(int blogID) { string userID = User.Identity.GetUserId(); FavoriteBlog checkFBlog = db.FavoriteBlogs.SingleOrDefault(b => b.BlogID == blogID && b.UserID == userID); try { // If post is already favorited, remove favorite if (checkFBlog != null) { db.FavoriteBlogs.Remove(checkFBlog); db.SaveChanges(); return(Json(new { success = true, isAdded = false, blogId = blogID })); } FavoriteBlog fBlog = new FavoriteBlog(); fBlog.BlogID = blogID; fBlog.UserID = userID; db.FavoriteBlogs.Add(fBlog); await db.SaveChangesAsync(); return(Json(new { success = true, isAdded = true, blogId = blogID })); } catch (Exception) { return(Json(new { success = false, msg = "An unknown error occured." })); } }
// Accept list of blogs, set isFavorite flag for each that user has favorited // Return list of blogs with flags set public ViewBlogViewModel checkFavorites(ViewBlogViewModel blog) { // If user is logged in, check if blog is favorited string userID = User.Identity.GetUserId(); if (!String.IsNullOrEmpty(userID)) { FavoriteBlog checkFBlog = db.FavoriteBlogs.SingleOrDefault(b => b.BlogID == blog.BlogID && b.UserID == userID); if (checkFBlog != null) { blog.isFavorited = true; } } return(blog); }