Beispiel #1
0
        public async Task <IActionResult> EditItem([FromBody] EditItemViewModel viewModel) //json input //move to api?
        {
            if (viewModel?.Id == null || viewModel?.Name == null || viewModel.Timestamp == null)
            {
                return(BadRequest("Введены некорректные данные."));
            }

            if (ModelState.IsValid)
            {
                OperationResult result;

                var product = _mapper.Map <Product>(viewModel);

                var catsIds = Enumerable.Empty <int>();
                if (viewModel.Categories != null)
                {
                    catsIds = viewModel.Categories
                              .Where(x => x.DtoState != DtoState.Deleted)
                              .Select(x => x.Id);
                }

                var descs = Enumerable.Empty <Description>();
                if (viewModel.DescriptionGroups != null)
                {
                    descs = _mapper.Map <IEnumerable <Description> >(viewModel.DescriptionGroups
                                                                     .SelectMany(x => x.DescriptionItems?.Where(i => i.DtoState != DtoState.Deleted)));
                }

                var images = Enumerable.Empty <Image>();
                if (viewModel.Images != null)
                {
                    images = _mapper.Map <IEnumerable <Image> >(viewModel.Images?
                                                                .Where(x => x.DtoState != DtoState.Deleted));
                }

                if (viewModel.CreateItem)
                {
                    result = await _shopManager.CreateProductAsync(product, images, catsIds, descs);
                }
                else
                {
                    result = await _shopManager.UpdateProductAsync(product, descs, catsIds, images);
                }

                if (result.Succeeded)
                {
                    TempData["Message"] = "Изменения успешно сохранены";
                    //provide relative address for redirect on ajax
                    return(Ok($"/{nameof(AdminController).Substring(0, 5)}/{nameof(ViewItem)}/{product.Id}"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }
            }

            var errors = ModelState.Values.SelectMany(v => v.Errors.Select(x => x.ErrorMessage));

            return(BadRequest(errors));
        }