Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1.         //Controller
  2.         [HttpPost]
  3.         public async Task<IActionResult> AddProduct(GiversAddProductVM giversAddProductVM)
  4.         {
  5.             if (!ModelState.IsValid)
  6.                 return View(giversAddProductVM);
  7.  
  8.             if (giversAddProductVM.Picture != null)
  9.             {
  10.                 var uniqueFileName = Helper.GetUniqueFileName(giversAddProductVM.Picture.FileName);
  11.                 var images = Path.Combine(hostingEnvironment.WebRootPath, "products");
  12.                 var filePath = Path.Combine(images, uniqueFileName);
  13.                 giversAddProductVM.Picture.CopyTo(new FileStream(filePath, FileMode.Create));
  14.                 giversAddProductVM.PictureFileName = uniqueFileName;
  15.             }
  16.  
  17.             await giversService.CreateProductAsync(giversAddProductVM);
  18.  
  19.             return RedirectToAction(nameof(AddProduct));
  20.         }
  21.    
  22.     //Service
  23.      public async Task CreateProductAsync(GiversAddProductVM giversAddProductVM)
  24.         {
  25.             await context.Product.AddAsync(new Product
  26.             {
  27.                 Picture = giversAddProductVM.PictureFileName,
  28.             });
  29.             await context.SaveChangesAsync();
  30.  
  31.         }
  32.  
  33.     //ViewModel
  34.     public class GiversAddProductVM
  35.     {
  36.        
  37.         public IFormFile Picture { get; set; }
  38.  
  39.         public string PictureFileName { get; set; }
  40.  
  41.        
  42.     }
  43.  
  44.     //View
  45. <form asp-controller="Givers" asp-action="AddProduct" method="post" enctype="multipart/form-data">
  46.     <img src="@Model.Picture" id="output" style="width: 200px; height: auto;" />
  47.     <br />
  48.         <input asp-for="Picture" type="file" accept="image/*;capture=camera" value="Lägg till bild" onchange="loadFile(event)">
  49.  
  50.     <input type="submit" value="Lägg till vara" />
  51. </form>
  52.  
  53. @section Scripts {
  54. <script>
  55. var loadFile = function (event) {
  56.     var output = document.getElementById('output');
  57.     output.src = URL.createObjectURL(event.target.files[0]);
  58. };
  59. </script>
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement