I have an Input tag like this:
<input type="file" name="file" accept="image/png, image/jpeg" class="choose">
<button id="bAddImage" type="button"> AddImage </button>
After the user clicks the bAddImage
button, if the user has selected a file, this file will be saved in an Array List in jQuery as follows:
$('body').on('click',
'#bAddImage',
function(event) {
event.preventDefault();
if ($('.choose')[0].files[0] == null) {
return;
}
IMAGES.push({
File: $('.choose')[0].files[0],
});
});
The problem I have here are the files in this list. These files will not be sent to the server after calling the method.
Class C#
public class AddProductRequest
{
public string ProductNameEn { get; set; }
public List<HttpPostedFileBase> ProductImages { get; set; }
}
Call Method in JavaScript
$('body').on('click',
'#bSubmit',
function(event) {
event.preventDefault();
var images = [];
if (IMAGES.length > 0) {
$.each(IMAGES,
function (index, item) {
images.push({
item.File
});
});
}
const formData = JSON.stringify({
ProductNameEn: 'test',
ProductImages: images *\\not send value*
});
$.ajax({
type: "POST",
url: '@Url.Action("AdminApiAddProduct", "CallApi", new {area = "AdminArea"})',
contentType: "application/json",
dataType: "json",
data: formData,
success: function (response) {
},
error: function () {
}
});
});
formData
in console.log
{"ProductNameEn":"test","ProductImages":["{}"]}
Sends ProductImages is null
while images
have a value.
images
in console.log
(1) […] 0: File { name: "test.png", lastModified: 1599110560934, size: 98288, … } length: 1 : Array [] script:1:151
Method in C#
[HttpPost]
public ActionResult AdminApiAddProduct(AddProductRequest request)
{
var nameEn = request.ProductNameEn; //test
if ((request.ProductImages ?? new List<HttpPostedFileBase>()).Count > 0)
{
**//Problem is NULL**
}
}
The whole problem I have is that the files selected by the user are not sent to the server and the value is ProductImages = null
.