示例#1
0
        public ActionResult Create(RecipeViewModel viewModel)
        {
            Recipe recipe = viewModel.Recipe;
            recipe.Category = repository.GetCategoryById(viewModel.CategoryID);
            recipe.SubCategoryID = viewModel.SubCategoryID;

            ValidateRecipeModel(recipe);

            if (ModelState.IsValid)
            {
                try
                {
                    repository.AddNewRecipe(recipe);
                }
                catch (DbEntityValidationException vex)
                {
                    //if the ModelState is valid, DbEntityValidationException can still occur when saving the data. The errors have to be logged and presented to the user.
                    foreach (var err in vex.EntityValidationErrors)
                    {
                        foreach (var innerError in err.ValidationErrors)
                        {
                            ModelState.AddModelError(string.Empty, innerError.ErrorMessage);
                        }
                    }
                }
                catch (DataException)
                {
                    ModelState.AddModelError(string.Empty, Constants.Constants.DataExceptionMessage);
                }

                return RedirectToAction("Index");
            }

            //Log errors to the database
            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    string s = error.ErrorMessage;
                }
            }
            return View(new RecipeViewModel(recipe, repository.GetAllCategories(),
                repository.GetSubCategoriesByCategoryId(recipe.Category.CategoryID), recipe.Category.CategoryID, recipe.SubCategoryID));
        }
示例#2
0
        public ActionResult Edit(RecipeViewModel model)
        {
            Recipe recipe = model.Recipe;
            var originalRecipe = GetRecipeByID(recipe.RecipeID);

            ValidateRecipeModel(recipe);

            var currentRecipe = repository.GetRecipeById(recipe.RecipeID);
            repository.SetEditedValues(currentRecipe, recipe);

            if (ModelState.IsValid)
            {
                repository.EditExistingRecipe(originalRecipe, recipe);
                return RedirectToAction("Index");
            }

            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    string s = error.ErrorMessage;
                }
            }

            return View(model);
        }