0

I have a service like this:

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "DoWork", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Person DoWork(Person person);
}

Service implementation is as follows:

public class Service : IService
{
    public Person DoWork(Person person)
    {
        //To do required function
        return person;
    }
}

My Person type definition is:

 [DataContract]
 public class Person
 {
    [DataMember]
    public string Name { get; set; }       
 }

I try to consume this service using jQuery:

   var data = { 'person': [{ 'Name': 'xxxxx'}] };

   $.ajax({
            type: "POST", 
            url: URL, // Location of the service
            data: JSON.stringify(data), //Data sent to server
            contentType: "application/json", // content type sent to server
            dataType: "json", //Expected data format from server
            processData: false,
            async: false,
            success: function (response) {                 
            },
            failure: function (xhr, status, error) {                   
                alert(xhr + " " + status + " " + error);
            }
        });

I can call the service using this, but the parameter (Person object) for the service method DoWork is always NULL. How can I fix this?

jwaliszko
  • 16,942
  • 22
  • 92
  • 158

1 Answers1

1

Your JavaScript data object is incorrectly constructed - it should be: { 'person': { 'Name': 'xxxxx' } }

What's more, you can choose alternative way of building JavaScript objects. The solution (which in my opinion is less error-prone) is to build objects in more standard manner (a bit more code, but less chance to be confused and make mistake - especially if the object has high complexity):

var data = new Object();
data.person = new Object();
data.person.Name = "xxxxx";

The last thing is, you missed to set up the body style of message that is sent to and from the service operation:

[WebInvoke(... BodyStyle = WebMessageBodyStyle.Wrapped)]
jwaliszko
  • 16,942
  • 22
  • 92
  • 158
  • I had tried this. Now also its not working. DoWork(Person person) method parameter is null. – user2567909 Jul 10 '13 at 10:40
  • I've edited the answer - I made a typo in `data` object construction. – jwaliszko Jul 10 '13 at 10:42
  • Now also service parameter is null only. Is it possible to pass parameter using json format, because I ave to access this service using java and antroid also – user2567909 Jul 10 '13 at 10:54
  • I know it is possible, I didn't said it is not. What's more, it should work. – jwaliszko Jul 10 '13 at 10:57
  • For further information take a look here (second paragraph): http://stackoverflow.com/questions/17489707/what-is-the-correct-url-for-service-reference/17492649#17492649. – jwaliszko Jul 10 '13 at 11:04