0

I have a model class like below:

public class clsUser
{
    public string FirstName{ get; set; }
    public String username { get; set; }
    public String password { get; set; }
    public List<ContactNumbers> Cnumbers{ get; set; }
}

Now i want to send ajax request with above model. i have tried to do same by using the following code:

  var dd =
   {

   "FirstName": "ABC",
   "username": "abc123",
   "password": "abc@123",
   "Cnumbers[0].Home":"0987654321",
   "Cnumbers[1].Company":"7654321"
   }

    var objInsertUser= JSON.stringify(dd);
    var URLValue = "http://localhost:47083/api/TestAPI/insertUser";
    $.ajax({
        type: "POST",
        url: URLValue,
        data: objInsertUser,
        contentType: "application/json",
        success: function (data) {
            alert(data);
        }

    });

But this always sending "Cnumbers" as null. i am not getting why..

If i am doing in wrong way could experts tell me the correct way..

thanks in advance.

2
  • Have you tried setting the ajax attribute dataType: 'json' ? Commented Apr 21, 2016 at 15:55
  • Your array will bind fine if you remove contentType: "application/json",and use data: dd (dont stringfy) Commented Apr 21, 2016 at 21:58

2 Answers 2

3

You need to create proper JSON. You need to create an array for Cnumbers

var dd = {
    "FirstName": "ABC",
    "username": "abc123",
    "password": "abc@123",
    "Cnumbers": [{
        "Home": "0987654321"
    }, {
        "Company": "7654321"
    }]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Add the stringify wrapper and inline the url around data: JSON.Stringify(objInsertUser), saves the extra lines.
@wadry, Yes, you are correct but thats not the problem area thus ignored.
0

The problem most likely lies in var objInsertUser= JSON.stringify(dd);. Your object is already JSON, so there's no need to stringfy it. data: dd, should be sufficient. When you Stringify already existing JSON you end up with default values for the parameters, and all non-primitives are null by default.

Also, as noted, your JSON is incorrect. Some people, when confronted with a problem, think "I know, I'll use JSON. Now you have two problems" XD. So, in summary: use correct JSON, and don't JSON.Stringify existing JSON.

1 Comment

This doesn't actually answer the question.

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.