1

I'm trying to post values to my WCF service via a jQuery AJAX call. Right now I have a single parameter that I'm trying to post. When I post the data, the correct service is called, but when I try to access the object str I get the error Object reference not set to an instance of an object. How can I fix this?

I've already looked here and here.

My code:

  $.ajax({
      type: "POST",
      url: '/api/addlocationfavorite',
      data: JSON.stringify({locationid: 543}),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      done: function (msg) {
          alert('done!');
      }
  });


<Runtime.Serialization.DataContract>
Public Class SimpleLocation
    <Runtime.Serialization.DataMember>
    Public Property locationid() As Integer
        Get
            Return locationid
        End Get
        Set(ByVal value As Integer)
            _locationid = value
        End Set
    End Property
    Private _locationid As Integer
End Class


    <OperationContract()>
    <Web.WebInvoke(Method:="POST", ResponseFormat:=Web.WebMessageFormat.Json, BodyStyle:=Web.WebMessageBodyStyle.WrappedRequest,
UriTemplate:="addlocationfavorite")>
    Function addLocationFavorite(ByVal str As SimpleLocation) As Stream 


   Public Function addLocationFavorite(ByVal str As SimpleLocation) As Stream Implements Ilocation.addLocationFavorite
        LogError("addLocationFavorite") '<-- this line is executed

        LogError("addLocationFavorite str.locationid: " + str.locationid.ToString) '<--- this line throws error: 'Object reference not set to an instance of an object.'

    End Function

I tried with and without quotes around the parameter name "locationid", but it shows the same error.

Adam
  • 6,041
  • 36
  • 120
  • 208

1 Answers1

1

In order for your method to accept the JSON object you will need to define it like so:

 { str: { locationid: 543 } }

'str' being the name of the parameter your method accepts, this will allow it to deserialize the JSON into your SimpleLocation object.

 $.ajax({
      type: "POST",
      url: '/api/addlocationfavorite',
      data: JSON.stringify({ str: { locationid: 543 } }), 
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      done: function (msg) {
          alert('done!');
      }
  });

The other problem here was with the locationid property. It was returning the property instead of the field.

Get
    Return locationid
End Get

it should be:

Get
    Return _locationid
End Get
Popo
  • 2,402
  • 5
  • 33
  • 55
  • Ok, doing that at least makes the `str` variable not nothing on the server side. However, when trying to access the `locationid` property of the `str` variable like so: `str.locationid.ToString` it returns value `0`. So it seems it's not being deserialized correctly? How to overcome that? – Adam Jun 02 '17 at 08:57
  • Wow...rookie mistake from me...but thanks, that did the trick :) – Adam Jun 03 '17 at 10:19