I have a partial view to display image upload button and a list of photos as follows:
<input type="file" id="FileUpload" multiple />
<input type="submit" id="Upload" value="Upload" />
<table class="table">
<!-- A table goes here to view the images from a table in the database using @foreach as below where Model is a list of images obtained from the database: -->
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.cover)
</td>
<td>
@Html.Image("/Images/" + item.id_product + "/" + item.id_product + ".jpg", "Image", "50")
@Html.DisplayFor(modelItem => item.Product.type)
</td>
</tr>
}
</table>
<script>
$(document).ready(function () {
$("#Upload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '/Products/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
});
});
</script>
My controller action that is supposed to receive the uploaded file is as follows:
[HttpPost]
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Server.MapPath("~/Images/");
if(this.CreateFolderIfNeeded(path))
file.SaveAs(path + fileName);
}
}
And in the main view I have the following:
@Ajax.ActionLink("All", "All", "Products", new { id = Model.id_product }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divImages",
InsertionMode = InsertionMode.Replace
})
<div id="divImages"></div>
And the all(int id)
method above is used to return a partial view with a list of images from the database.
Now, I have the following requirement:
After the user click on the upload button, I want to pass a parameter (@Model.Take(1).Single().id_product
) to the ActionMethod
Upload()
in the controller to save the path (which is named according to @Model.Take(1).Single().id_product
) of the uploaded image in the database.
Also I want after the image is uploaded successfully, I want to refresh the partial view (table) automatically to view the newly uploaded image.
I hope someone can help.