I have an ASP.NET MVC 5 application. And I'm trying to send a POST request with the Model data, and also include user selected files. Here is my ViewModel (simplified for clarity):
public class Model
{
public string Text { get; set; }
public long Id { get; set; }
}
Here is the controller Action:
[HttpPost]
public ActionResult UploadFile(long userId, Model model)
{
foreach (string file in Request.Files)
{
// process files
}
return View("Index");
}
Html input element:
<div>
<input type="file" name="UploadFile" id="txtUploadFile" />
</div>
And the JavaScript code:
$('#txtUploadFile').on('change', function (e) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
data.append("userId", 1);
data.append("model", JSON.stringify({ Text: 'test text', Id: 3 }));
$.ajax({
type: "POST",
url: '/Home/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (result) { },
error: function (xhr, status, p3, p4) { }
});
});
The problem is that when the Request reaches controller action, I have files and 'userId' populated, but 'model' parameter is always null. Am I doing something wrong when populating FormData object?