2

Please see the code below:

<head runat="server">
    <title></title>

    <script type="text/javascript"  src="Javascript/json2.js"></script>
    <script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script>

    <script type = "text/javascript">


        Test();
        function Test() {
            alert("got here 1");
            $.ajax({
                type: "POST",
                url: "AjaxObjectTest.aspx/Test",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess(),
            async: false,
            failure: function (response) {
                alert('there was an error counting possibles')
            }
        });

        function OnSuccess() {
            return function (response) {
                var data = response.d;
                alert(data.name);
            }
        }
    }
    </script>

</head>

The asp.net code looks like this:

Public Class Person
    Public id As Integer
    Public age As Integer
    Public name As String
End Class

Public Class AjaxObjectTest
    Inherits System.Web.UI.Page

    <System.Web.Services.WebMethod()> _
    Public Shared Function Test() As Person
        Dim p1 As Person = New Person
        p1.id = 1
        p1.age = 34
        p1.name = "Mark"
        Return p1
    End Function

End Class

Please see this link: https://msdn.microsoft.com/en-us/library/ms733127(v=vs.110).aspx

I don't have to add a DataMember attribute to the Person class and I do not have add a Data Contract attribute to the attributes i.e. Person.ID, Person.Age and Person.Name in order for it to work.

Why is this?

Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36
w0051977
  • 15,099
  • 32
  • 152
  • 329

2 Answers2

1

DataContract and DataMember are attributes used on WCF services to describe a service metadata, in your case you aren't using an actual "web service" you are just exposing a method to be used and behaive as web service.

see below topic to know when you should use them DataContract & DataMember When to use DataContract and DataMember attributes?

Community
  • 1
  • 1
  • Thanks. That is what I thought, however I could not find any docs to support it. I assume that these attributes are not needed for asmx web services either? +1 – w0051977 Jul 02 '16 at 18:06
  • That's right. those only used in WCF service to make it more controllable and flexible – Mohammad Al Safra Jul 02 '16 at 18:18
0

From the link you sent (https://msdn.microsoft.com/en-us/library/ms733127(v=vs.110).aspx):

By default, the DataContractSerializer infers the data contract and serializes all publicly visible types.

Your fields are probably public… So by default the serializer puts them in the response. In order to select the fields serialized, you must use the DataContractAttribute and IgnoreDataMemberAttribute on the fields you want to ignore.

Romain
  • 812
  • 6
  • 8