4

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?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
user0810
  • 886
  • 5
  • 19
  • 33
  • can you check with the debugger what really is sent to your server via `Request.Form`, also you could try to add `[FromForm]` to your action parameters. – Isparia Feb 17 '20 at 15:54
  • I checked `HttpContext.Request.Form.AllKeys` and there is no variable `document`... – user0810 Feb 17 '20 at 16:06

2 Answers2

1

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'}) 
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

By default, model binding gets data in the form of key-value pairs, assuming both are strings. Files are an exception.

You can pass key-value pairs like this

formData.append('document.title', document.title)

Alternatively, you can build a custom model binder. Like it is described in this SO.

Pavel Shastov
  • 2,657
  • 1
  • 18
  • 26