[SOLVED] Upload image in ASP.NET MVC 5 EF6

Issue

I’ve had a look at some other questions and tutorials, but I’m struggling to incorporate the suggestions into my existing work.

I want the user to be able to upload an image in a submission form for a new listing, my listing model looks like this;

public class Listing
{
    public int ListingID { get; set; }
    [Display(Name = "Select Category")]
    public int CategoryID { get; set; }
    [Display(Name = "Select Vendor")]
    public int VendorID { get; set; }
    [Required]
    [Display(Name = "Listing Name")]
    public string ListingName { get; set; }
    [Required]
    [Display(Name = "Listing Description")]
    public string ListingDesc { get; set; }
    [Required]
    [Display(Name = "Maximum Capacity")]
    public int Capacity { get; set; }
    [Required]
    [DataType(DataType.Currency)]
    [Display(Name = "Price")]
    public decimal Price { get; set; }
    [Required]
    [Display(Name = "Fixed Price?")]
    public bool IsFixedPrice { get; set; }
    [Required]
    public string Address { get; set; }
    [Display(Name = "Address Line 2")]
    public string Address2 { get; set; }
    [Required]
    public string City { get; set; }
    [Required]
    public string Postcode { get; set; }

    public virtual Category Category { get; set; }
    public virtual Vendor Vendor { get; set; }

}

I have a separate controller, the create method is as follows;

// GET: Listing/Create
    public ActionResult Create()
    {
        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
        ViewBag.VendorID = new SelectList(db.Vendors, "ID", "CompanyName");
        return View();
    }

    // POST: Listing/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ListingID,CategoryID,VendorID,ListingName,ListingDesc,Capacity,Price,IsFixedPrice,Address,Address2,City,Postcode")] Listing listing)
    {
        if (ModelState.IsValid)
        {
            db.Listings.Add(listing);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", listing.CategoryID);
        ViewBag.VendorID = new SelectList(db.Vendors, "ID", "CompanyName", listing.VendorID);
        return View(listing);
    }

Any direction on how I can implement this seemingly fairly simple task into the my existing code would be greatly appreciated!

Solution

I found a solution that works that allows me to upload a single file to an Uploads directory.

My model has remained unchanged.

The controller was updated to include;

HttpPostedFileBase file

And;

if (file.ContentLength > 0)
        {
            string fileName = Path.GetFileName(file.FileName);
            string directory = Server.MapPath("~/Content/uploads/");
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string path = Path.Combine(directory, fileName);
            file.SaveAs(path);

        }

Which in context of my original code forms this;

// POST: Listing/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ListingID,CategoryID,VendorID,ListingName,ListingDesc,Capacity,Price,IsFixedPrice,Address,Address2,City,Postcode")] Listing listing, HttpPostedFileBase file)
    {

        if (file.ContentLength > 0)
        {
            string fileName = Path.GetFileName(file.FileName);
            string directory = Server.MapPath("~/Content/uploads/");
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string path = Path.Combine(directory, fileName);
            file.SaveAs(path);

            //var fileName = Path.GetFileName(file.FileName);
            //var path = Path.Combine(Server.MapPath("~/Content/Uploads"));
            //file.SaveAs(path);
        }

        if (ModelState.IsValid)
        {

            db.Listings.Add(listing);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", listing.CategoryID);
        ViewBag.VendorID = new SelectList(db.Vendors, "ID", "CompanyName", listing.VendorID);
        return View(listing);
    }

In my create view, I added;

 @using (Html.BeginForm("Create", "Listing", FormMethod.Post, new { enctype = "multipart/form-data" }))

And;

<input type="file" name="file" id="file" />
<input type="submit" value="submit" />

This works for me, however, I’ve not tested to see how it performs when attempting to view each individual listing ID, so this might not be the correct solution for me.

Answered By – Mostly

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *