Example #1
0
        public async Task <IActionResult> Create(RecipeCreateInputModel input)
        {
            var isExist = this.recipesService.IsExistRecipeTitle(input.Title);

            if (isExist)
            {
                this.ViewData["Errors"] += RecipeExistNameError + "\r\n";
            }

            var isAtLeastChecked = false;

            foreach (var cookingMethod in input.CookingMethods)
            {
                if (cookingMethod.Selected)
                {
                    isAtLeastChecked = true;
                    break;
                }
            }

            var isValidIngredients = true;

            foreach (var ingredientName in input.IngredientsNames.Split("\r\n", StringSplitOptions.RemoveEmptyEntries))
            {
                if (ingredientName.Length > AttributesConstraints.IngredientNameMaxLength ||
                    ingredientName.Length < AttributesConstraints.IngredientNameMinLength)
                {
                    isValidIngredients       = false;
                    this.ViewData["Errors"] += IngredientNameError + "\r\n";
                    break;
                }
            }

            if (!this.ModelState.IsValid || !isAtLeastChecked || isExist || !isValidIngredients)
            {
                var categories     = this.categoriesService.GetAll <RecipeCreateCategoryDropDownViewModel>();
                var cuisines       = this.cuisinesService.GetAll <RecipeCreateCuisineDropDownViewModel>();
                var cookingMethods = this.cookingMethodsService.GetAll <RecipeCreateCookingMethodsCheckboxViewModel>();

                input.Categories     = categories;
                input.Cuisines       = cuisines;
                input.CookingMethods = cookingMethods;

                return(this.View(input));
            }

            var user = await this.userManager.GetUserAsync(this.User);

            var serviceModel = new RecipeCreateServiceModel
            {
                Title            = input.Title,
                AuthorId         = user.Id,
                Description      = input.Description,
                Advices          = input.Advices,
                Servings         = input.Servings,
                PrepTime         = input.PrepTime,
                CookTime         = input.CookTime,
                SeasonalType     = input.SeasonalType,
                SkillLevel       = input.SkillLevel,
                CategoryId       = input.CategoryId,
                CuisineId        = input.CuisineId,
                Images           = input.Images,
                TitleImage       = input.TitleImage,
                IngredientsNames = input.IngredientsNames,
                CookingMethods   = input.CookingMethods,
            };

            int recipeId = await this.recipesService.AddAsync(serviceModel);

            this.TempData["SuccessCreateRecipe"] = SuccessCreateRecipe;

            return(this.Redirect("/"));
        }