I am still very much a begineer in ASP.Net. I stumble about and occasionally something clicks and I can get a lot of what I need done.
But this is frustrating me chronically. What I want to do is add to an existing model the ability to upload an image to the web and retrieve as part of the final 'report' I will generate. I have been having a pass at this now and again using tutorials I find online but none seems to actually work without little red squiggles, so I am either stupid, or the tutorials are for different virgins or ...probably stupid.
The code I am trying to make work this time are:
Extract from Equipment Model:
[Display(Name = "Equipment Type")] public int EqTypeID { get; set; } [Display(Name ="Equipment Photo")] [DataType(DataType.ImageUrl)] public string ImageUrl { get; set; } public int Quantity { get; set; } [Display(Name = "Manufacturer")] public int MakeID { get; set; }
I then have a view model ImageViewModel, which I copied form the tutorial:
namespace Eva804.Models { public class ImageViewModel { [Required] public string Title { get; set; } public string AltText { get; set; } [DataType(DataType.Html)] public string Caption { get; set; } [DataType(DataType.Upload)] IFormFile ImageUpload { get; set; } } }
Following the tutorial broadly I have the following controller:
public async Task<IActionResult> Create( [Bind("ConditionID,EqTypeID,EstimateRemainingLife,InstallDate,EquipmentImage, LastServiceDate,MakeID,Model,Notes,Recommended,ReplacementCost,SerialNumber,WaterBodyID")] Equipment equipment, ImageViewModel model) { try { var validImageTypes = new string[] {"image/gif","image/jpeg","image/pjpeg","image/png" }; if (!validImageTypes.Contains(model.ImageUpload.ContentType)) { ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image."); } if (ModelState.IsValid) { if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0) { var uploadDir = "~/uploads" var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName); var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName); model.ImageUpload.SaveAs(imagePath); image.ImageUrl = imageUrl; } _context.Add(equipment); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } }
Which is hating ImageUpload, Server.Mappath and image.Imageurl.
Clearly this is wrong.
Where can I go for good tutorial? I really have struggled with this?