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.

6
  • append each key/value pair Commented Jul 17, 2019 at 10:02
  • From the code provided you don't attach the form data to the xmlhttprequest object. Commented Jul 17, 2019 at 10:04
  • @Dimitar, I missed to mention that, but that is not the issue in our side. Commented Jul 17, 2019 at 10:13
  • Your ajax.open still looks wrong (see my answer): is this just another mistake here? Did you inspect your network traffic to see if the problem is on the client or on the server side? Commented Jul 17, 2019 at 10:21
  • @KarthikRavichandran and you have missed what you have as "server side". MVC, Web Api, something else ? Please provide all the necessary infomation, so people can help you. Commented Jul 17, 2019 at 10:35

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

If we set the argument type as string it receives properly. shall we changed the type with strongly defined class instead of string? because multiple data will be sent to server
Can you provide the args (string data).
Please check the attached links which might help you.

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.