Esempio n. 1
0
        public async Task <IActionResult> AddTodoItem(AddTodoItemViewModel addTodoItemViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            // create an ImageForCreation instance
            var todoItemForCreationViewModel = new TodoItemForCreationViewModel()
            {
                Name = addTodoItemViewModel.Name
            };

            // serialize it
            var serializedTodoItemForCreationViewModel = JsonConvert.SerializeObject(todoItemForCreationViewModel);

            // call the API
            var httpClient = await _iTodoApiHttpClient.GetClient();

            var response = await httpClient.PostAsync(
                $"api/todoitems",
                new StringContent(serializedTodoItemForCreationViewModel, Encoding.Unicode, "application/json"))
                           .ConfigureAwait(false);

            return(HandleApiResponse(response, () => RedirectToAction("Index")));
        }
        public IActionResult CreateTodoItems([FromBody] TodoItemForCreationViewModel todoItemForCreationViewModel)
        {
            if (todoItemForCreationViewModel == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                // return 422 - Unprocessable Entity when validation fails
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var todoItem = Mapper.Map <Entities.TodoItem>(todoItemForCreationViewModel);

            var ownerId = User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;

            todoItem.OwnerId = ownerId;

            // add and save.
            _todoRepository.AddTodoItem(todoItem);

            if (!_todoRepository.Save())
            {
                throw new Exception($"Adding an todoitem failed on save.");
            }

            var todoItemViewModel = Mapper.Map <TodoItemViewModel>(todoItem);

            return(CreatedAtRoute("GetTodoItem",
                                  new { id = todoItemViewModel.Id },
                                  todoItemViewModel));
        }