public async Task <string> AddMobile(AddMobileDto model) { try { var mobile = new Models.Mobile.Mobile { Name = model.Name, Size = model.Size, Weight = model.Weight, Resolution = model.Resolution, Processor = model.Processor, Memory = model.Memory, OperatingSystem = model.OperatingSystem, Price = model.Price, Manufacturer = await _context.Manufacturers.FirstOrDefaultAsync(m => m.Id == model.Manufacturer) }; await _context.Mobiles.AddAsync(mobile); await _context.SaveChangesAsync(); var path = Path.Combine(_env.WebRootPath, "files", $"{mobile.Id}"); var pathConst = path; if (model.ThumbNail != null) { path = Path.Combine(pathConst, "thumbnail"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (var stream = new FileStream(Path.Combine(path, model.ThumbNail.FileName.Split('\\').Last()), FileMode.Create)) { model.ThumbNail.CopyTo(stream); var mobileThumbnail = new MobileThumbnail { MobileId = mobile.Id, Src = $"/files/{mobile.Id}/thumbnail/{model.ThumbNail.FileName.Split('\\').Last()}" }; await _context.MobileThumbnail.AddAsync(mobileThumbnail); } } if (model.Images != null) { foreach (var image in model.Images) { path = Path.Combine(pathConst, "images"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (var stream = new FileStream(Path.Combine(path, image.FileName.Split('\\').Last()), FileMode.Create)) { image.CopyTo(stream); var mobileImage = new MobileImage { MobileId = mobile.Id, Src = $"/files/{mobile.Id}/images/{image.FileName.Split('\\').Last()}" }; await _context.MobileImages.AddAsync(mobileImage); } } } if (model.Videos != null) { foreach (var video in model.Videos) { path = Path.Combine(pathConst, "videos"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (var stream = new FileStream(Path.Combine(path, video.FileName.Split('\\').Last()), FileMode.Create)) { video.CopyTo(stream); var mobileVideo = new MobileVideo { MobileId = mobile.Id, Src = $"/files/{mobile.Id}/videos/{video.FileName.Split('\\').Last()}" }; await _context.MobileVideos.AddAsync(mobileVideo); } } } await _context.SaveChangesAsync(); return("success"); } catch { return("fail"); } }
public async Task <IActionResult> AddRedirect([FromForm] AddMobileDto model) { var addResult = await _mobile.AddMobile(model); return(RedirectToAction(addResult.Equals("success") ? "Index" : "Error")); }