Exemplo n.º 1
0
        public async Task <IActionResult> Create(CreateCategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                var identityUser = await _userManager.GetUserAsync(HttpContext.User);

                string path = "/img/no_image.jpg";
                if (model.TitleImage != null)
                {
                    FileSaverResult fileSaverResult = await _fileSaver.SaveCategoryTitleImage(_appEnvironment.WebRootPath, model.TitleImage);

                    if (fileSaverResult.IsSuccessful)
                    {
                        path = fileSaverResult.Path;
                    }
                    else
                    {
                        ModelState.AddModelError("", "Can't save image");
                    }
                }

                var result = await Mediator.Send(new CreateCategoryCommand
                {
                    Title          = model.Title,
                    IdentityUserId = identityUser.Id,
                    TitleImagePath = path,
                });

                if (result.IsSuccessful)
                {
                    if (model.TitleImage != null)
                    {
                        using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
                        {
                            await model.TitleImage.CopyToAsync(fileStream);
                        }
                    }
                    return(RedirectToAction("Index", "Category"));
                }
                else
                {
                    ModelState.AddModelError("", result.Message);
                }
            }
            return(View());
        }