Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Controller
- [HttpPost]
- public async Task<IActionResult> AddProduct(GiversAddProductVM giversAddProductVM)
- {
- if (!ModelState.IsValid)
- return View(giversAddProductVM);
- if (giversAddProductVM.Picture != null)
- {
- var uniqueFileName = Helper.GetUniqueFileName(giversAddProductVM.Picture.FileName);
- var images = Path.Combine(hostingEnvironment.WebRootPath, "products");
- var filePath = Path.Combine(images, uniqueFileName);
- giversAddProductVM.Picture.CopyTo(new FileStream(filePath, FileMode.Create));
- giversAddProductVM.PictureFileName = uniqueFileName;
- }
- await giversService.CreateProductAsync(giversAddProductVM);
- return RedirectToAction(nameof(AddProduct));
- }
- //Service
- public async Task CreateProductAsync(GiversAddProductVM giversAddProductVM)
- {
- await context.Product.AddAsync(new Product
- {
- Picture = giversAddProductVM.PictureFileName,
- });
- await context.SaveChangesAsync();
- }
- //ViewModel
- public class GiversAddProductVM
- {
- public IFormFile Picture { get; set; }
- public string PictureFileName { get; set; }
- }
- //View
- <form asp-controller="Givers" asp-action="AddProduct" method="post" enctype="multipart/form-data">
- <img src="@Model.Picture" id="output" style="width: 200px; height: auto;" />
- <br />
- <input asp-for="Picture" type="file" accept="image/*;capture=camera" value="Lägg till bild" onchange="loadFile(event)">
- <input type="submit" value="Lägg till vara" />
- </form>
- @section Scripts {
- <script>
- var loadFile = function (event) {
- var output = document.getElementById('output');
- output.src = URL.createObjectURL(event.target.files[0]);
- };
- </script>
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement