I have application made with React Native, and the backend API is in .NET C#. I am trying to send some data from frontend to backend
reactjs
let formData = new FormData();
formData.append('token', token)
formData.append('document', document)
formData.append('file', file);
Where token
is a string, file
is some file, but document
is an object with params like Id
and Name
. So on backend I receive the data like this
C#
[HttpPost]
[AllowAnonymous]
public ActionResult SendDocument(string token, DocumentMobile document, HttpPostedFileBase file)
{
//do thins
}
The problem is that object document
is not converted to DocumentMobile
model, like it used to do without using FormData
, and all props inside are null.
How to do this?
You need to bind each properties of your class, that's how the model binder is working, it is looking for the name of the properties of your class. So depends on the structure of your document
class, one of the following should works in your case:
formData.append('Id', document.Id)
formData.append('Name', document.Name)
Or this:
formData.append('document', {Id: document.Id, Name: document.Name})
Or:
formdata.append("document[id]", document.Id)
formdata.append("document[name]", document.Name)
And for file you might want to use something like this:
formData.append('file', {uri: file, name: 'image.jpg', type: 'image/jpeg'})