mercredi 29 juin 2016

FormData in asp .net mvc with file upload and other data than files

I am trying to upload an image in asp .net mvc using FormData for a specific item in my database. For that I need to send along with the image the id of the item in the database to link the image to.

I need to use FormData because I need the page not to be refreshed. So I am using jquery for ajax with the image.

I added the id of the image using formdata.append but I get an error in the server which tells me that the id parameter of the method that is called when doing ajax request, is not nullable and so it can't be mapped. It should be mapped to the id of the item in the database I mentioned earlier.

But I added in the form data the id of the item.

This is my javascript code:

var formData = new FormData();
var totalFiles = document.getElementById("inputImage").files.length;
formData.append("categoryId", response.data.toString());
for (var i = 0; i < totalFiles; i++) {
    var file = document.getElementById("inputImage").files[i];
    formData.append("categoryImage", file);
}
$.ajax("@Url.Action("SaveCategoryImage", "Categories")",
{
    type: "POST",
    dataType: "JSON",
    data: formData,
    contentType: false,
    processData: false,
    headers: { __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val() }
});

And this is the method in the controller that should get called:

public async Task<ActionResult> SaveCategoryImage(long cateogoryId, HttpPostedFileBase image)
{
    return new JsonNetResult(new BasicActionResultViewModel {IsSuccessful = true});
}

So why doesn't asp .net mvc map the id I send in the form data to the id in the method of the controller?

Aucun commentaire:

Enregistrer un commentaire