WellThisIsAkward WellThisIsAkward - 6 days ago 7
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

View



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

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

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

</div>
<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 })" />*@
</div>
<p><input type="submit" value="Create" /></p>
</form>
</fieldset>
}
<div>


Controller



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

}

[HttpPost]
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;

}
repository.Create(Image);
}
}
return RedirectToAction("Index");

}


Model



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


EFRepositoty

public void Create(Image Image)
{


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

}
}
context.SaveChanges();

}

Answer

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

if(!ModelState.IsValud)
    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.

Comments