Aymen Kareem Aymen Kareem - 1 month ago 22
Ajax Question

Passing Image file and a parameter from Ajax to MVC Controller

Here is my partial view:

<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 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.

Answer

This is Stephen Muecke comment above. It services as answer to my question. I copied and pasted here so that people can see it:

If you wrap your file input and submit button in a tag, then you can use just var formdata = new FormData($('form').get(0)); then you can add an additional value using formdata,append(id: 'yourValue'); And change the method to public void Upload(IEnumerable files, int ID) (and give the file input a name attribute - name="files"`)

Comments