Advertisement
Guest User

123

a guest
Feb 26th, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.10 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Mvc;
  9. using ProjectApplicationX00140684.Models;
  10. using Microsoft.AspNetCore.Mvc.Infrastructure;
  11.  
  12. namespace ProjectApplicationX00140684.Controllers
  13. {
  14.  
  15. public class HomeController : Controller
  16. {
  17. private readonly IVehicleRepository _vehicleRepository;
  18. private readonly IHostingEnvironment hostingEnvironment;
  19.  
  20. public HomeController(IVehicleRepository vehicleRepository,
  21. IHostingEnvironment hostingEnvironment)
  22. {
  23. _vehicleRepository = vehicleRepository;
  24. this.hostingEnvironment = hostingEnvironment;
  25. }
  26.  
  27. public ViewResult Index()
  28. {
  29. var model = _vehicleRepository.GetAllVehicle();
  30. return View(model);
  31. }
  32.  
  33. [HttpGet]
  34. public ViewResult Create()
  35. {
  36. return View();
  37. }
  38.  
  39. [HttpPost]
  40. public IActionResult Create(VehicleCreateViewModel model)
  41. {
  42. if (ModelState.IsValid)
  43. {
  44. string uniqueFileName = null;
  45.  
  46. // If the Photo property on the incoming model object is not null, then the user
  47. // has selected an image to upload.
  48. if (model.Photo != null)
  49. {
  50. // The image must be uploaded to the images folder in wwwroot
  51. // To get the path of the wwwroot folder we are using the inject
  52. // HostingEnvironment service provided by ASP.NET Core
  53. string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
  54. // To make sure the file name is unique we are appending a new
  55. // GUID value and and an underscore to the file name
  56. uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName);
  57. string filePath = Path.Combine(uploadsFolder, uniqueFileName);
  58. // Use CopyTo() method provided by IFormFile interface to
  59. // copy the file to wwwroot/images folder
  60. model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
  61. }
  62.  
  63. Vehicle newVehicle = new Vehicle
  64. {
  65.  
  66. Make = model.Make,
  67. Model = model.Model,
  68. Year = model.Year,
  69. // Store the file name in PhotoPath property of the employee object
  70. // which gets saved to the Employees database table
  71. PhotoPath = uniqueFileName
  72. };
  73.  
  74. _vehicleRepository.Add(newVehicle);
  75. return RedirectToAction("index", new { id = newVehicle.VehicleID });
  76. }
  77.  
  78. return View();
  79. }
  80. }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement