public async Task <IActionResult> Create([Bind("Id,Name,Address,PostalCode,Email,CellPhone")] DogBreeder dogBreeder) { if (ModelState.IsValid) { _context.Add(dogBreeder); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(dogBreeder)); }
public async Task <IActionResult> Create([Bind("Id,NameOfPhoto,Date,Local,DogFK")] Photos photos, IFormFile photoOfDog) { /* * Algorithm to deal with file of photos of dogs * - if there is no file, * - do not accept the record * - write it to user, at browser * - if the file was not good (.png ,.jpg are good files) * - do not accept the record * - write it to user, at browser * - if you came to here, is because the file is good * - decide the name of file * - assign the file name to data colected by the form * - write the file on the disc drive */ if (photoOfDog == null) { // if you came to here, there is no file // write a error message ModelState.AddModelError("", "you haven't choose a file. Please, pick one..."); // send the control to Browser ViewData["Dogs"] = new SelectList(_db.Dogs.OrderBy(d => d.Name), "Id", "Name"); return(View()); } if (photoOfDog.ContentType != "image/jpeg" && photoOfDog.ContentType != "image/png") { // if you came to here, there is a file // but, the file is not good // write a error message ModelState.AddModelError("", "Your file is not of correct type. Please, choose PNG or JPG image..."); // send the control to Browser ViewData["Dogs"] = new SelectList(_db.Dogs.OrderBy(d => d.Name), "Id", "Name"); return(View()); } // if you came to here, you have a good file... //Decide the name of your file Guid g; g = Guid.NewGuid(); // determining the extension of file string extension = Path.GetExtension(photoOfDog.FileName).ToLower(); // new name of file string nameOfFile = photos.DogFK + "_" + g.ToString() + extension; // assign new file name to 'photos' photos.NameOfPhoto = nameOfFile; if (ModelState.IsValid) { _db.Add(photos); await _db.SaveChangesAsync(); // because all data was stored on DB, // we are going to store de file on the disc drive of server // Where you want the file to be stored? string whereToStoreTheFile = _path.WebRootPath; nameOfFile = Path.Combine(whereToStoreTheFile, "fotos", nameOfFile); // write the file using var stream = new FileStream(nameOfFile, FileMode.Create); await photoOfDog.CopyToAsync(stream); return(RedirectToAction(nameof(Index))); } ViewData["DogFK"] = new SelectList(_db.Dogs, "Id", "Id", photos.DogFK); return(View(photos)); }