-2

I am posting data to my asp controller using fetch API with:

    var data1 = {ID: '1', Name: 'John'},
    data2 = {ID: '1',Action: 'Add'};
   fetch('myController/MyAction',{method: 'post',body: JSON.stringify({data1: data1, data2: data2})});

I have my controller action like:

public async Task<IActionResult>MyAction([FromBody]Data1 data1, [FromBody]Data2 data2)
{
//break
//do something with data1
// do something with data2
}

I can see In Developer Tools, the data is being passed. But In VS debugger, I see both objects' all properties null. Please note that, if I send only data1 or data data2, model is bound successfully.

  • 1
    Have you tried `JSON.stringify()` to same object you are constructing for the jQuery `data` property? – Taplar Apr 07 '20 at 22:47
  • 2
    `JSON.stringify({Master: master, Flag: flag})` – Get Off My Lawn Apr 07 '20 at 22:57
  • Possible duplicate of [Post a x-www-form-urlencoded request from React Native](https://stackoverflow.com/questions/35325370/post-a-x-www-form-urlencoded-request-from-react-native). Ignore the accepted answer though and go with the top voted – Phil Apr 07 '20 at 23:16
  • Is it possible for you to change the controller code? – Yousuf Khan Apr 10 '20 at 06:19
  • @YousufKhan Yes! By the way, I tried adding data2 as a property in my data1 model class and that was fine. But I am afraid it will be problematic when I will move ahead to add more models and logic... – Jahanzaib Muhammad Apr 10 '20 at 10:25
  • @JahanzaibMuhammad I always expect a single object in my controller and add as many props as that single object. So for example it'll be `async TaskMyAction([FromBody]Data data)` and the `Data` class can contain all your properties like `Data1, Data2...` and so on – Yousuf Khan Apr 10 '20 at 10:34

1 Answers1

0

This would work if you can modify your controller

public async Task<IActionResult>MyAction([FromBody]Data data)
{
//break
//do something with data1
// do something with data2
}

and

var data1 = {ID: '1', Name: 'John'},
    data2 = {ID: '1',Action: 'Add'};
   fetch('myController/MyAction',{method: 'post',body: JSON.stringify({data1: data1, data2: data2})});

You can add two properties data1 & data2 to the class Data.

This approach seems easy and improves code readability as well. You controller expects a single object in the request and that object can contain as much data as you want.

Yousuf Khan
  • 334
  • 3
  • 12
  • Good Idea! Please let me discuss it with my mate. But I am amazed that I was able to send and catch two object with jQuery.ajax and I did not have to stringify my js objects whereas my data type was json. – Jahanzaib Muhammad Apr 11 '20 at 10:51