WellThisIsAkward WellThisIsAkward - 1 year ago 65
C# Question

multiple image upload loop only adding one image id and path database

Hi every one I am trying to create an mvc application that allows the user to upload multiple photos to a folder and saves the Id and path in the database. Currently my application adds all the files to the folder but only adds the last selected image id and path to the database.

Thanks for any help with this problem


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

<form action="" method="post" enctype="multipart/form-data">

<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)

<div class="editor-field">
<input id="ImagePath" title="Upload a product image" multiple="multiple" type="file" name="files" />

@*<img class="img-thumbnail" width="150" height="150" src="@Url.Action("GetImage", "Home",new { Model.ID })" />*@
<p><input type="submit" value="Create" /></p>


public ViewResult Create()
return View("Create", new Image());


public ActionResult Create(Image Image, IEnumerable<HttpPostedFileBase> files)

if (ModelState.IsValid)

foreach (var file in files)
if (file.ContentLength > 0)

file.SaveAs(HttpContext.Server.MapPath("~/Img/") + file.FileName);
Image.ImagePath = file.FileName;

return RedirectToAction("Index");



public partial class Image
public int ID { get; set; }
public string ImagePath { get; set; }


public void Create(Image Image)

if (Image.ID == 0)
Image dbEntry = context.Images.Find(Image.ID);
if (dbEntry != null)
dbEntry.ImagePath = Image.ImagePath;



Answer Source

This is because you are redirecting to index inside your loop so it only processes the first file. Move your ModelState.IsValid check outside of the loop

    return View();

And then put redirect to last line of method.

What's happening with the Image entity is when its saved the first time the object is given an ID then for each other file in the loop it's just updating the same record in the database, this is why you will only see the last file in the db.

At the end of each loop you should set the image = null will fix things.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download