Пример #1
0
        public ActionResult Form(AlimentoViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            var alimento = new Alimento();

            alimento           = Mapper.Map <Alimento>(viewModel);
            alimento.UsuarioId = User.Identity.GetUserId();
            alimento.DataHora  = viewModel.ObterDataCompleta();

            var result = alimento.Validar();

            if (!result.IsValid)
            {
                foreach (var validation in result.Errors)
                {
                    if (validation.PropertyName.Equals("DataHora"))
                    {
                        ModelState.AddModelError("", validation.ErrorMessage);
                    }
                    else
                    {
                        ModelState.AddModelError(validation.PropertyName, validation.ErrorMessage);
                    }
                }
                return(View(viewModel));
            }

            if (string.IsNullOrEmpty(alimento.Id))
            {
                _unitOfWork.AlimentoRepository.Add(alimento);
            }
            else
            {
                _unitOfWork.AlimentoRepository.Update(alimento);
            }

            _unitOfWork.Commit();

            return(RedirectToAction("Index"));
        }