MVC5 Uploading images and saving the path to db.
I have a product class with
public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public ProductCategory ProductCategory { get; set; } //Navigation property public int ProductCategoryId { get; set; } //FK public string ImagePath { get; set; } }
I have a view the takes input for all the properties except for the imagepath. To upload the image I have used <input type=file > tag. What I want is:
- Rename the uploaded image to Product's
Nameproperty. Such that if product is called Laptop then the image is Laptop.jpg. - Store the image in my
/Uploads/Imagesdirectory. - Get the image path i.e
/Uploads/Images/Laptop.jpgand store it the product'sImagePathproperty.
My current view is:
@using (Html.BeginForm("Save","Products")) { //code removed to save space //I take input here using @Html.TextBoxFor(model => model.Product.Name) and so on <input type="file" required/> . . <input type="submit" value="Submit" class="btn btn-default" /> }
So when the user submits, the view send the data over to my Save controller . Here's whats in there:
public ActionResult Save(Product product) { if (!ModelState.IsValid) //If the validation fails. { var viewModel = new ProductFormViewModel { Product = product, ProductCategories = _context.ProductCategories.ToList() }; return View("ProductForm", viewModel); } //i think i need to do something here to save the image onto my Images directory? but not sure how _context.Products.Add(product); _context.SaveChanges(); return RedirectToAction("Index", "Home"); }
What can i do to get this working? Any help would be appreciated. Thanks!
0 comments:
Post a Comment