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?

2
  • 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. Commented Feb 17, 2020 at 15:54
  • I checked HttpContext.Request.Form.AllKeys and there is no variable document... Commented Feb 17, 2020 at 16:06

2 Answers 2

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'}) 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.