Пример #1
0
        //public RedirectToActionResult Create(Employee employee)
        public IActionResult Create(HomeCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = UploadAvatar(model);

                //Multiple upload
                //if (model.Photos != null && model.Photos.Count > 0)
                //{
                //    foreach(IFormFile photo in model.Photos)
                //    {
                //        string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                //        uniqueFileName = $"{Guid.NewGuid().ToString()}_{photo.FileName}";
                //        var filePath = Path.Combine(uploadFolder, uniqueFileName);
                //        photo.CopyTo(new FileStream(filePath, FileMode.Create));
                //    }
                //}
                Employee newEmp = new Employee()
                {
                    AvatarPath  = uniqueFileName ?? $"nonavatar.png",
                    Department  = model.Department,
                    Email       = model.Email,
                    Name        = model.Name,
                    PhoneNumber = null
                };
                employeeRepository.Add(newEmp);
                return(RedirectToAction("details", new { id = newEmp.Id }));
            }
            return(View());
        }
Пример #2
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var flower = new Flower()
                {
                    Name = model.Name,

                    TypeF = model.TypeF
                };
                var fileName = string.Empty;
                if (model.Avatar != null)
                {
                    string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                    fileName = $"{Guid.NewGuid()}_{model.Avatar.FileName}";
                    var filePath = Path.Combine(uploadFolder, fileName);
                    using (var fs = new FileStream(filePath, FileMode.Create))
                    {
                        model.Avatar.CopyTo(fs);
                    }
                }
                flower.AvatarPath = fileName;
                var newEmp = flowerRepository.Create(flower);
                return(RedirectToAction("Details", new { id = newEmp.Id }));
            }
            return(View());
        }
Пример #3
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var student = new Cake()
                {
                    nameCake  = model.nameCake,
                    ThanhPhan = model.ThanhPhan,

                    Hsd        = model.Hsd,
                    Nsx        = model.Nsx,
                    GiaBan     = model.GiaBan,
                    DaXoa      = model.DaXoa,
                    CategoryId = model.CategoryId
                };

                var newStd = studentRepository.Create(student);
                if (newStd != null)
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            //ViewBag.Classes = GetClasses();
            return(View());
        }
Пример #4
0
 public IActionResult Create(HomeCreateViewModel model)
 {
     if (ModelState.IsValid)
     {
         var product = new Product()
         {
             ProductName          = model.ProductName,
             Description          = model.Description,
             Price                = model.Price,
             Count                = model.Count,
             CategoriesCategoryId = model.CategoryId
         };
         var fileName = string.Empty;
         if (model.ProductImage != null)
         {
             string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
             fileName = $"{Guid.NewGuid()}_{model.ProductImage.FileName}";
             var filePath = Path.Combine(uploadFolder, fileName);
             using (var fs = new FileStream(filePath, FileMode.Create))
             {
                 model.ProductImage.CopyTo(fs);
             }
         }
         product.ProductImage = fileName;
         var newPrd = productRepository.Create(product);
         return(RedirectToAction("Index", "Product", new { id = newPrd.ProductId }));
     }
     return(View());
 }
Пример #5
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var employee = new Employee()
                {
                    Name       = model.Name,
                    Email      = model.Email,
                    Department = model.Department
                };

                var fileName = string.Empty;
                if (model.Avatar != null)
                {
                    string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                    fileName = $"{Guid.NewGuid()}_{model.Avatar.FileName}";
                    var filePath = Path.Combine(uploadFolder, fileName);
                    using (var fs = new FileStream(filePath, FileMode.Create))
                    {
                        model.Avatar.CopyTo(fs);
                    }
                }
                else
                {
                    fileName = "nonavatar.jpg";
                }
                employee.AvatarPath = fileName;
                var newEmp = employeeRepository.Create(employee);
                return(RedirectToAction("Details", new { id = newEmp.Id }));
            }
            return(View());
        }
Пример #6
0
 public IActionResult Create(HomeCreateViewModel model)
 {
     if (ModelState.IsValid)
     {
         var employee = new Employee()
         {
             Department = model.Department,
             Email      = model.Email,
             Name       = model.Name
         };
         var uniqueFileName = string.Empty;
         if (model.Photo != null)
         {
             var folderPath = Path.Combine(webHostEnvironment.WebRootPath, "images");
             uniqueFileName = $"{Guid.NewGuid()}_{model.Photo.FileName}";
             //uniqueFileName = model.Photo.FileName;
             var filePath = Path.Combine(folderPath, uniqueFileName);
             using (var fileName = new FileStream(filePath, FileMode.Create))
             {
                 model.Photo.CopyTo(fileName);
             }
         }
         employee.AvatarPath = uniqueFileName;
         var newEmp = employeeRepository.Create(employee);
         return(RedirectToAction("Details", new { id = newEmp.Id }));
     }
     return(View());
 }
Пример #7
0
        public IActionResult Create(HomeCreateViewModel newemployee)
        {
            if (ModelState.IsValid)
            {
                string        UniqueFileName = null;
                List <string> fileNames      = new List <string>();
                if (newemployee.FileName != null && newemployee.FileName.Count > 0)
                {
                    string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "Files");
                    foreach (var file in newemployee.FileName)
                    {
                        UniqueFileName = Guid.NewGuid() + "_" + file.FileName;
                        string filePath = Path.Combine(uploadsFolder, UniqueFileName);
                        file.CopyTo(new FileStream(filePath, FileMode.Create));
                        fileNames.Add(UniqueFileName);
                    }
                    //UniqueFileName = Guid.NewGuid() + "_" + newemployee.FileName.ForEach;
                    //string filePath = Path.Combine(uploadsFolder, UniqueFileName);
                    //newemployee.FileName.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                Employee empValue = _employeeRepository.AddEmployee(new Employee {
                    Name       = newemployee.Name,
                    Department = newemployee.Department,
                    FileName   = fileNames.Count() > 0 ? String.Join(';', fileNames) : null
                });

                return(new RedirectToActionResult("Details", "Home", new { id = empValue.ID }));
            }

            return(View());
        }
Пример #8
0
        public IActionResult Create()
        {
            Tag[] tagsFromDb             = _appContext.Tags.ToArray();
            List <HomeTagViewModel> tags = new List <HomeTagViewModel>();

            Status[] statusesFromDb        = _appContext.Statuses.ToArray();
            List <SelectListItem> statuses = new List <SelectListItem>();

            foreach (var item in tagsFromDb)
            {
                tags.Add(new HomeTagViewModel()
                {
                    Id   = item.Id,
                    Name = item.Naam
                });
            }
            foreach (var item in statusesFromDb)
            {
                statuses.Add(new SelectListItem()
                {
                    Value = item.Id.ToString(),
                    Text  = item.Naam
                });
            }

            HomeCreateViewModel model = new HomeCreateViewModel()
            {
                Tags     = tags,
                Statuses = statuses
            };

            return(View(model));
        }
Пример #9
0
        private string ProcessUploadedFile(HomeCreateViewModel model)
        {
            string uniqueFileName = null;

            // If the Photo property on the incoming model object is not null, then the user
            // has selected an image to upload.
            if (model.Photo != null)
            {
                // The image must be uploaded to the images folder in wwwroot
                // To get the path of the wwwroot folder we are using the inject
                // HostingEnvironment service provided by ASP.NET Core
                string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
                // To make sure the file name is unique we are appending a new
                // GUID value and and an underscore to the file name
                uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                // Use CopyTo() method provided by IFormFile interface to
                // copy the file to wwwroot/images folder
                //model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    model.Photo.CopyTo(fileStream);
                }
            }

            return(uniqueFileName);
        }
Пример #10
0
        public IActionResult Index(HomeCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var symptom = new Symptom()
                {
                    Fever      = model.Sot,
                    Sob        = model.Sob,
                    Nausea     = model.Nausea,
                    Sorethroat = model.Sorethroat,
                    Skinrash   = model.Skinrash,
                    Bots       = model.Bots,
                    Cough      = model.Cough,
                    Diarhea    = model.Diarhea
                };
                int symptomId = symptomRepository.Create(symptom);
                var dedical   = new Medical_Declaration()
                {
                    UserName       = model.UserName,
                    GateId         = model.GateId,
                    Dob            = model.Dob,
                    Gender         = model.Gender,
                    Phone          = model.Phone,
                    Email          = model.Email,
                    Address        = model.Address,
                    SymptonId      = symptomId,
                    PassportNumber = model.PassportNumber,
                    ProvinceId     = model.ProvinceId,
                    DistrictId     = model.DistrictId,
                    WardId         = model.WardId,
                    Description    = model.Description,
                    Departure_day  = model.Departure_day,
                    Entry_date     = model.Entry_date,
                    start_place    = model.Start_Place,
                    destination    = model.Destination,
                    Contact_Oj     = model.Contact_Oj,
                    Contact_Pp     = model.Contact_Pp,
                    vacxin         = model.Vacxin
                };
                var newmedical = medicalRepository.Create(dedical);
                return(RedirectToAction("Privacy", "Home"));

                ;
            }
            var wards = wardRepository.Gets().ToList();

            ViewBag.wards = wards;
            var districts = districtRepository.Gets().ToList();

            ViewBag.districts = districts;
            var provinces = provinceRepository.Gets().ToList();

            ViewBag.provinces = provinces;
            var gates = gateRepository.Gets().ToList();

            ViewBag.gates = gates;
            return(View(model));
        }
Пример #11
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            //if (ModelState.IsValid)
            //{
            //    Employee newEmployee = this._employeeRepository.addEmployee(employee);
            //    return RedirectToAction("details", new { id = newEmployee.Id });
            //}
            //else
            //{
            //    return View();
            //}

            if (ModelState.IsValid)
            {
                #region save with single file upload


                string uniqueFileName = ProcessUploadedFile(model);
                #endregion

                #region save with single file upload


                //string uniqueFileName = null;

                // If the Photo property on the incoming model object is not null, then the user
                // has selected an image to upload.
                //if (model.Photos != null && model.Photos.Count > 0)
                //{
                //    foreach (IFormFile photo in model.Photos)
                //    {
                //        string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
                //        uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                //        string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                //        photo.CopyTo(new FileStream(filePath, FileMode.Create));
                //    }

                //}
                #endregion
                Employee newEmployee = new Employee
                {
                    Name       = model.Name,
                    Email      = model.Email,
                    Department = model.Department,
                    // Store the file name in PhotoPath property of the employee object
                    // which gets saved to the Employees database table
                    PhotoPath = uniqueFileName
                };

                _employeeRepository.addEmployee(newEmployee);
                return(RedirectToAction("details", new { id = newEmployee.Id }));
            }

            return(View());
        }
Пример #12
0
        public async Task <IActionResult> Index()
        {
            var vm = new HomeCreateViewModel
            {
                ProductCount = await _bll.Products.CountProductsInShop(User.GetShopId()),
                UserCount    = await _bll.AppUsers.CountUsersInShop(User.GetShopId()),
                OrderCount   = await _bll.Orders.CountOrdersInShop(User.GetShopId())
            };

            return(View(vm));
        }
Пример #13
0
        private string FileUploadProcess(HomeCreateViewModel model)
        {
            string uniqueFileName = null;

            if (model.Photo != null)
            {
                string uploadFolderPath = Path.Combine(hostingEnvironment.WebRootPath, "Images");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                string uploaddFile = Path.Combine(uploadFolderPath, uniqueFileName);
                using (FileStream fileStream = new FileStream(uploaddFile, FileMode.Create))
                {
                    model.Photo.CopyTo(fileStream);
                }
            }
            return(uniqueFileName);
        }
Пример #14
0
 public IActionResult Create(HomeCreateViewModel model)
 {
     if (ModelState.IsValid)
     {
         string   uniqueFileName = ProcessPhoto(model);
         Employee newEmployee    = new Employee()
         {
             Name       = model.Name,
             Email      = model.Email,
             Department = model.Department,
             PhotoPath  = uniqueFileName
         };
         _employeeRepository.AddEmployee(newEmployee);
         return(RedirectToAction("Details", new { id = newEmployee.Id }));
     }
     return(View());
 }
Пример #15
0
        private string UploadAvatar(HomeCreateViewModel model)
        {
            var uniqueFileName = string.Empty;

            //Single upload
            if (model.Photo != null)
            {
                string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                uniqueFileName = $"{Guid.NewGuid()}_{model.Photo.FileName}";
                var filePath = Path.Combine(uploadFolder, uniqueFileName);
                using (var fileName = new FileStream(filePath, FileMode.Create))
                {
                    model.Photo.CopyTo(fileName);
                }
            }

            return(uniqueFileName);
        }
Пример #16
0
 public IActionResult Create(HomeCreateViewModel model)
 {
     if (ModelState.IsValid)
     {
         var student = new Student()
         {
             Fullname = model.Fullname,
             DoB      = model.DoB,
             Gender   = model.Gender,
             Email    = model.Email,
             ClassId  = model.ClassId
         };
         var newStd = studentRepository.Create(student);
         return(RedirectToAction("Index", "Home"));
     }
     ViewBag.Classes = GetClasses();
     return(View());
 }
Пример #17
0
        public async Task <IActionResult> Create(HomeCreateViewModel model)
        {
            if (!TryValidateModel(model))
            {
                return(View(model));
            }


            var project = new Project()
            {
                Titel        = model.Titel,
                Beschrijving = model.Beschrijving,
                StatusId     = int.Parse(model.SelectedStatus),
            };

            using (var memoryStream = new MemoryStream())
            {
                await model.Foto.CopyToAsync(memoryStream);

                project.Foto = memoryStream.ToArray();
            }


            _appContext.Projects.Add(project);
            _appContext.SaveChanges();
            foreach (var item in model.Tags)
            {
                if (item.Checked)
                {
                    var tagProject = new TagProject()
                    {
                        ProjectId = project.Id,
                        TagId     = item.Id
                    };
                    _appContext.TagProjects.Add(tagProject);
                    _appContext.SaveChanges();
                }
            }



            return(RedirectToAction("Index"));
        }
Пример #18
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            string uniqueFileName = null;

            if (ModelState.IsValid)
            {
                string   uploadFolderPath = FileUploadProcess(model);
                Employee emp = new Employee()
                {
                    Name      = model.Name,
                    Email     = model.Email,
                    Deparment = model.Deparment,
                    PhotoPath = uniqueFileName
                };
                _employeeRepository.AddEmployee(emp);
                return(RedirectToAction("Details", new { id = emp.ID }));
            }
            return(View());
        }
Пример #19
0
        private string ProcessUploadFile(HomeCreateViewModel model)
        {
            string uniqueFileName = null;

            if (model.Photo != null)
            {
                if (model.Photo.ContentType == "image/jpeg" ||
                    model.Photo.ContentType == "image/png" ||
                    model.Photo.ContentType == "image/gif")
                {
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                    string filePath      = Path.Combine(uploadsFolder, uniqueFileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        model.Photo.CopyTo(fileStream);
                    }
                }
            }
            return(uniqueFileName);
        }
Пример #20
0
        public async Task <IActionResult> Create(HomeCreateViewModel model)
        {
            if (!TryValidateModel(model))
            {
                return(View(model));
            }
            var film = new Film()
            {
                Titel        = model.Titel,
                Beschrijving = model.Beschrijving,
            };

            using (var memoryStream = new MemoryStream())
            {
                await model.Foto.CopyToAsync(memoryStream);

                film.Foto = memoryStream.ToArray();
            }
            _appContext.Films.Add(film);
            _appContext.SaveChanges();
            return(RedirectToAction("AdminPage"));
        }
Пример #21
0
        public IActionResult Create()
        {
            var viewModel = new HomeCreateViewModel
            {
                Options = new List <Option>
                {
                    new Option {
                        Id = 1, OptionText = "Option 1"
                    },
                    new Option {
                        Id = 2, OptionText = "Option 2"
                    },
                    new Option {
                        Id = 3, OptionText = "Option 3"
                    },
                    new Option {
                        Id = 4, OptionText = "Option 4"
                    }
                }
            };

            return(View(viewModel));
        }
 public IActionResult Create(HomeCreateViewModel model)
 {
     if (ModelState.IsValid)
     {
         var balo = new Balo()
         {
             BaloName    = model.BaloName,
             Trademark   = model.Trademark,
             Size        = model.Size,
             Material    = model.Material,
             Description = model.Description,
             Price       = model.Price,
             CategoryId  = model.CategoryId,
             Color       = model.Color,
             Sale        = model.Sale,
             KeySearch   = $"{model.BaloName.ToLower()} {model.Description.ToLower()} {model.Trademark.ToLower()} " +
                           $"{categoryRepository.Get(model.CategoryId).CategoryName.ToLower()}"
         };
         var fileName = string.Empty;
         if (model.Image != null)
         {
             string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images/balos");
             fileName = $"{Guid.NewGuid()}_{model.Image.FileName}";
             var filePath = Path.Combine(uploadFolder, fileName);
             using (var fs = new FileStream(filePath, FileMode.Create))
             {
                 model.Image.CopyTo(fs);
             }
         }
         balo.Image = fileName;
         var newEmp = baloRepository.Create(balo);
         ViewBag.Categories = GetCategories();
         return(RedirectToAction("Index", "ProductsManage"));
     }
     ViewBag.Categories = GetCategories();
     return(View());
 }
Пример #23
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            var product = new Product()
            {
                Name        = model.Name,
                Brand       = model.Brand,
                Radius      = model.Radius,
                Thickness   = model.Thickness,
                Cord        = model.Cord,
                Glasses     = model.Glasses,
                water_proof = model.water_proof,
                Guarantee   = model.Guarantee,
                Price       = model.Price,
                CategoryId  = model.CategoryId
            };
            var fileName = string.Empty;

            if (model.AvatarPath != null)
            {
                string uploadFoder = Path.Combine(webHostEnvironment.WebRootPath, "img");
                fileName = $"{Guid.NewGuid()}_{ model.AvatarPath.FileName}";
                var filePath = Path.Combine(uploadFoder, fileName);
                using (var fs = new FileStream(filePath, FileMode.Create))
                {
                    model.AvatarPath.CopyTo(fs);
                }
            }
            else
            {
                fileName = "anh9.jpg";
            }

            product.Avatar = fileName;
            var newPrd = productRepository.Create(product);

            return(RedirectToAction("Details", new { id = newPrd.Id }));
        }
Пример #24
0
        public IActionResult Create(HomeCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                uniqueFileName = ProcessUploadFile(model);
                #region Multiple Photo Uploads
                //if (model.Photos != null && model.Photos.Count > 0)
                //{
                //    foreach (IFormFile photo in model.Photos)
                //    {
                //        if(photo.ContentType == "image/jpeg"
                //            || photo.ContentType == "image/png"
                //            || photo.ContentType == "image/gif")
                //        {
                //            uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                //            string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                //            string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                //            photo.CopyTo(new FileStream(filePath, FileMode.Create));
                //        }
                //    }
                //}
                #endregion

                Employee newEmployee = new Employee
                {
                    Name       = model.Name,
                    Email      = model.Email,
                    Department = model.Department,
                    PhotoPath  = uniqueFileName
                };

                _employeeRepository.Add(newEmployee);
                return(RedirectToAction("Details", "Home", new { id = newEmployee.Id }));
            }
            return(View());
        }
        public IActionResult Create(HomeCreateViewModel model)
        {
            var userId = this.userManager.GetUserId(this.User);

            if (this.homes.Exists(userId))
            {
                return(this.RedirectToAction("Index", "Home"));
            }

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

            if (model.Pictures == null || model.Pictures.Count == 0)
            {
                this.ModelState.AddModelError("Pictures", "You need to add at least 1 picture of your home.");
                return(this.View(model));
            }

            List <string> picturesPaths = new List <string>();

            //save pictures
            var homePicturesPath = this.GetAdequateHomePicturesPath();

            foreach (var picture in model.Pictures)
            {
                if (picture.Length > 0)
                {
                    var pictureFullPath = Path.Combine(homePicturesPath, picture.FileName);

                    using (var stream = new FileStream(pictureFullPath, FileMode.Create))
                    {
                        Task.Run(async() =>
                        {
                            await picture.CopyToAsync(stream);
                        }).Wait();

                        var pathTokens = pictureFullPath
                                         .Split(new[] { "\\" }, StringSplitOptions.None);

                        var relativePicturePath = string.Join("/", pathTokens.Skip(pathTokens.Length - 2));

                        picturesPaths.Add(relativePicturePath);
                    }
                }
            }

            this.homes.Create(
                model.Country,
                model.City,
                model.Address,
                model.Sleeps.Value,
                model.Bedrooms.Value,
                model.Bathrooms.Value,
                model.PricePerNight,
                model.Additionalnformation,
                model.IsActiveOffer,
                picturesPaths,
                userId);

            this.users.AddInRole(userId, ApplicationConstants.HostRole);

            return(RedirectToAction("Index", "Home"));
        }
Пример #26
0
        public async Task <IActionResult> Create(HomeCreateViewModel data)
        {
            var allQUestions = questionsRepository.GetAll(); //Get all the Question(s)

            //Only 10 Questions are allowed at a time
            if (allQUestions.Count >= 10)
            {
                ModelState.AddModelError("", "Oops only 10 questions can be added at the moment");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    //Create the Question Object that is used to Create the Question in the database
                    var question = new Questions
                    {
                        QuestionText  = data.QuestionText,
                        CorrectOption = data.CorrectOption
                    };

                    var createdQuestion = await questionsRepository.Create(question);//Create the Question

                    //A list containing the options that will be stored in the database
                    List <Options> optionsList = new List <Options>();

                    //Create a list that stores all the Options the User Created for the Question
                    List <string> optionText = new List <string>
                    {
                        data.Option1,
                        data.Option2,
                        data.Option3,
                        data.Option4
                    };

                    //Add items to the Option list
                    for (int i = 0; i < 4; i++)
                    {
                        optionsList.Add(
                            new Options
                        {
                            OptionText = optionText[i],
                            QuestionId = createdQuestion.QuestionId
                        });
                    }

                    await optionsRepository.Create(optionsList);//Create the Options

                    return(RedirectToAction("Index"));
                }
            }

            //Error occured while creating, create and return the Option list again
            data.Options = new List <Option>
            {
                new Option {
                    Id = 1, OptionText = "Option 1"
                },
                new Option {
                    Id = 2, OptionText = "Option 2"
                },
                new Option {
                    Id = 3, OptionText = "Option 3"
                },
                new Option {
                    Id = 4, OptionText = "Option 4"
                }
            };
            ModelState.AddModelError("", "Error occured while creating please create again");
            return(View(data));
        }
Пример #27
0
        public IActionResult Create(HomeCreateViewModel homeCreateViewModel)
        {
            if (ModelState.IsValid)
            {
                var recipeModel             = homeCreateViewModel.RecipeModel;
                var ingredientModels        = homeCreateViewModel.IngredientModels;
                var recipeIngredientsModels = homeCreateViewModel.RecipeIngredientModels;
                var instructionModels       = homeCreateViewModel.InstructionModels;

                if (ingredientModels != null)
                {
                    var index = 0;
                    foreach (var ingredientModel in ingredientModels)
                    {
                        // Check for existing ingredient
                        IngredientModel existingIngredient = _db.Ingredients.FirstOrDefault(x => x.Ingredient == ingredientModel.Ingredient);
                        if (existingIngredient != null)
                        {
                            recipeIngredientsModels[index].IngredientId = existingIngredient.Id;
                        }
                        else
                        {
                            recipeIngredientsModels[index].IngredientsModel = ingredientModel;
                        }
                        index++;
                    }
                }

                string FileName = null;
                if (homeCreateViewModel.Photo != null)
                {
                    var imageFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images", "uploadedImages");
                    FileName = $"{Guid.NewGuid()}_{homeCreateViewModel.Photo.FileName}";
                    var path = Path.Combine(imageFolder, FileName);
                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        homeCreateViewModel.Photo.CopyTo(fileStream);
                    }
                    recipeModel.RecipeInfoModel.PhotoPath = FileName;
                }

                var userId = _userManager.GetUserId(User);

                var newRecipe = new RecipeModel
                {
                    RecipeName             = recipeModel.RecipeName,
                    RecipeDescription      = recipeModel.RecipeDescription,
                    RecipeType             = recipeModel.RecipeType,
                    CreatedDate            = recipeModel.CreatedDate,
                    RecipeIngredientModels = recipeIngredientsModels,
                    InstructionModels      = instructionModels,
                    RecipeInfoModel        = recipeModel.RecipeInfoModel,
                    AuthorId = userId
                };

                _db.Add(newRecipe);
                _db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View());
        }