Aymen Kareem Aymen Kareem - 2 months ago 23
jQuery Question

How to Pass Image File and Some Data From Ajax to MVC Controller

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) {
@Html.DisplayFor(modelItem => item.cover)
@Html.Image("/Images/" + item.id_product + "/" + item.id_product + ".jpg", "Image", "50")
@Html.DisplayFor(modelItem => item.Product.type)

$(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);
type: "POST",
url: '/Products/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
error: function (error) {


My controller action that is supposed to receive the uploaded file is as follows:

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/");
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 (
) to the
in the controller to save the path (which is named according to
) 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.


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"`)