I want to send JSON data to my WCF Service, but in the Service there is my object always null. I have read so many articles but I can’t solve my problem.
[WebInvoke(UriTemplate = "/POST/PersonPost", Method = "POST",BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public Person InsertPerson(Person per)
{ Debug.WriteLine("InsertPerson");
if (per == null)
{
return new Person("2", "null");
}
Debug.WriteLine("POST:[PersonId = {0} PersonName = {1}]", per.Id, per.Name);
return new Person("1", "InsertPerson");
}
[DataContract]
public class Person
{
public Person(string id, string name)
{
this.id = id;
this.name = name;
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
public override string ToString()
{
var json = JsonConvert.SerializeObject(this);
return json.ToString();
}
}
and here my jQuery:
var person = {};
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
var param = JSON.stringify(per);
//param = "{"per":{"Id":"abc123","Name":"aaaa"}}"
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
processData: false,
crossDomain: true,
url: "http://localhost:59291/Person/POST/PersonPost",
success: function (data) {
alert("Post erfolgreich: ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText);
}
});
What is there wrong? Why is my parameter per in the insertPerson method always null.
Try this:
var person = {};
person.id = "1";
person.name = "abc";
var param = JSON.stringify(person);
One of the reasons, you are receiving your request object as null because, the method is expecting an object of type Person. This in JSON is as follows according to your definition of Person.
{"id": "1", "name": "abc"}
This is because there is nothing like per inside Person.
Person person = New Person("1", "abc");
person.per //There is nothing defined as per inside person.
Your web site is breaking the Same Origin Policy
Heres Ways to circumvent the same-origin policy
Your setting crossDomain to true
, but this is only compatible with jsonp, read this
sorry my english, this work for me:
var LstPerson = new Array();
var person = {};
person.Id = 1
person.name = 'abc'
LstPerson.push(person)
var param = JSON.stringify(LstPerson);
send only [{“id”: “1”, “name”: “abc”}] from JS, and WCF REST definition:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public Person InsertPerson(List<Person> per)