Example #1
0
        public async Task <IActionResult> Edit(int?id, EditThoughtViewModel model)
        {
            if (!id.HasValue)
            {
                return(BadRequest("No thought ID was provided"));
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var thought = _mapper.Map <Thought>(model);

            thought.Id = id.Value;

            // get new thought image
            var imagePath = await UploadImage(HttpContext.Request.Form.Files);

            if (imagePath != null)
            {
                // remove old image from file system
                _fileManager.DeleteFile(thought.Image);
                //set new image path
                thought.Image = imagePath;
            }

            // update thought
            _repository.UpdateThought(thought);

            var updatedThought = await _repository.GetThoughtByIdAsync(id.Value);

            if (updatedThought == null)
            {
                _logger.LogInformation($"Unable to retrieve thought for id {id}");
                return(View("Error"));
            }

            if (await UserIsThoughtAuthorAsync(updatedThought))
            {
                if (await _repository.CommitChangesAsync())
                {
                    var thoughtUrl = GetThoughtUrl(thought);
                    TempData["success"] = "Thought successfully saved";
                    return(Redirect(thoughtUrl));
                }
                else
                {
                    _logger.LogError($"Issue saving changes for thought with id: {thought.Id}");
                    TempData["error"] = "There was an issue saving your changes";
                    return(RedirectToAction("Manage"));
                }
            }

            // user is not thought author
            return(Forbid());
        }
        public EditThoughtViewModel GetEditThought(int thoughtId)
        {
            var thoughtDto = this.thoughtService.GetThought(thoughtId);
            var viewModel  = new EditThoughtViewModel()
            {
                Id            = thoughtDto.ThoughtId,
                DateTime      = thoughtDto.Timeframe.TimeframeDateTime,
                Description   = thoughtDto.Description,
                TimeframeType = thoughtDto.Timeframe.TimeframeType
            };

            return(viewModel);
        }