5

We need to send the data to the server by appending it within formdata in javascript. In javascript, we have handle this as like below.

var ajax = new XMLHttpRequest();
ajax.open("POST", url, true);
var formData = new FormData();
var obj = {url: "uploadUrl",type: 'POST', mode: true};
formData.append('myData', JSON.stringify(obj));
ajax.send(formData);

In server end, we have the method as like below.

 public void Save(MyModel args) {
     ....
    }


    public class MyModel
    {

        public MyObj myData { get; set; }

    }
    public class MyObj
    {
        public string url { get; set; }
        public string type { get; set; }
        public bool mode { get; set; }
    }

args.myData always received as null. How to receive the data sent from the client here in this format ? Suggest your ideas.

Karthik Ravichandran
  • 1,205
  • 2
  • 15
  • 25

2 Answers2

2

You need to explicitly send the formData:

var ajax = new XMLHttpRequest();
ajax.open('POST', url, true);
var formData = new FormData();
var obj = {url: "uploadUrl",type: 'POST', mode: true};
formData.append('myData', obj);
ajax.send(formData);

(Note that I fixed the arg order in ajax.open and the received formdata will be something like [object Object] but I think JSON.stringify() should be the solution here - that depends on how your server parses the formdata)

Jb31
  • 1,381
  • 1
  • 10
  • 19
1

In server code, set the type of args to String and check if you are getting the stringified data. If you are getting it, parse the data accordingly to fit into MyModel.

Providing more info of Server code might help me to look into further.

EDIT 1: Links that might also help

Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43