public IActionResult Profile() { var dbUser = _db.Users.FirstOrDefault(u => u.Id == HttpContext.Session.GetInt32("_Userid")); if (dbUser == null) { return(RedirectToAction("Login")); } var dbRecipes = _db.Recipes.Where(r => r.UploaderId == dbUser.Id).ToList(); var recipeCount = 0; var recipeIds = new List <int>(); if (dbRecipes.Count > 0) { foreach (var recipe in dbRecipes) { recipeIds.Add(recipe.Id); } recipeCount = dbRecipes.Count; } var dbUserBio = _db.UserBios.FirstOrDefault(b => b.UserId == dbUser.Id); var bio = ""; if (dbUserBio != null) { bio = dbUserBio.Bio; } var dbUserRatings = _db.RecipeRatings.Where(r => recipeIds.Contains(r.RecipeId)).ToList(); var numberRatings = 0; var avgRating = 0; if (dbUserRatings.Count > 0) { numberRatings = dbUserRatings.Count; foreach (var rating in dbUserRatings) { avgRating += rating.Rating; } avgRating = avgRating / dbUserRatings.Count; } var model = new ProfileViewModel { DisplayName = dbUser.DisplayName, Username = dbUser.Username, UserId = dbUser.Id, Email = dbUser.Email, Rating = avgRating, NumberRecipes = recipeCount, NumberRatings = numberRatings, Bio = bio }; ViewData["Recipes"] = dbRecipes; return(View(model)); }
public IActionResult UserProfile(int id) { // this controller method is for viewing a user's profile that is not your own var dbUser = _db.Users.FirstOrDefault(u => u.Id == id); if (dbUser == null) { RedirectToAction("NoneFound"); } var dbRecipes = _db.Recipes.Where(r => r.UploaderId == dbUser.Id).ToList(); var recipeCount = 0; var recipeIds = new List <int>(); if (dbRecipes.Count > 0) { foreach (var recipe in dbRecipes) { recipeIds.Add(recipe.Id); } recipeCount = dbRecipes.Count; } var dbUserBio = _db.UserBios.FirstOrDefault(b => b.UserId == dbUser.Id); var bio = ""; if (dbUserBio != null) { bio = dbUserBio.Bio; } var dbUserRatings = _db.RecipeRatings.Where(r => recipeIds.Contains(r.RecipeId)).ToList(); var numberRatings = 0; var avgRating = 0; if (dbUserRatings.Count > 0) { numberRatings = dbUserRatings.Count; foreach (var rating in dbUserRatings) { avgRating += rating.Rating; } avgRating = avgRating / dbUserRatings.Count; } if (dbUser == null) { return(View("/")); } var model = new ProfileViewModel { DisplayName = dbUser.DisplayName, Username = dbUser.Username, UserId = dbUser.Id, Email = dbUser.Email, Rating = avgRating, NumberRecipes = recipeCount, NumberRatings = numberRatings, Bio = bio }; ViewData["Recipes"] = dbRecipes; return(View(model)); }