public async Task <IActionResult> Create( [Bind("Name,Description,MinAmountOfPlayers," + "TimeOfPassing,MaxAmountOfPlayers," + "PhoneNumber,Rating,LevelOfFear,LevelOfDifficulty")] Room room) { try { if (ModelState.IsValid) { context.Rooms.Add(room); await context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log. ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator."); } return(View(room)); }
public async Task <IActionResult> Create( [Bind("Name,Description,MinAmountOfPlayers," + "Address,TimeOfPassing,MaxAmountOfPlayers,MinAge," + "PhoneNumber,Email,Company,Rating,LevelOfFear,LevelOfDifficulty,Files")] RoomViewModel rvm) { Room room = rvm; room.Images = new List <Image>(); try { if (ModelState.IsValid) { if (rvm.Files.Count > 0) { foreach (var image in rvm.Files) { Image img = new Image(); var stream = image.OpenReadStream(); if (FileHelper.IsValidFileExtensionAndSignature(image.FileName, stream, _permittedExtensions)) { if (stream.Length > _fileSizeLimit) { var megabyteSizeLimit = _fileSizeLimit / 1048576; ModelState.AddModelError("Files", $"One or more files exceed {megabyteSizeLimit:N1} MB"); return(View(room)); } string path = Path.Combine(HostingEnvironment.WebRootPath, "images\\" + room.Name); if (!Directory.Exists(path)) { DirectoryInfo di = Directory.CreateDirectory(path); } string fullPath = Path.Combine(path, image.FileName); stream = new FileStream(fullPath, FileMode.Create); using (var binaryWriter = new BinaryWriter(stream)) { using (var binaryReader = new BinaryReader(image.OpenReadStream())) { binaryWriter.Write(binaryReader.ReadBytes((int)image.Length)); } } var pic = System.Drawing.Image.FromFile(fullPath); img.Name = image.FileName; img.Path = fullPath.Substring(fullPath.IndexOf("images")); img.ContentType = image.ContentType; img.Height = pic.Height; img.Width = pic.Width; room.Images.Add(img); } else { ModelState.AddModelError("Files", "One or more files have wrong type"); return(View(room)); } } } context.Rooms.Add(room); await context.SaveChangesAsync(); return(Redirect("/")); } } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log. ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator."); } return(View(room)); }