I have developed a Rest service in WCF (demo), which provides me with the following output:
{"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}}
Now, I have created an ASP.NET website where I am utilizing AJAX JSON to call this rest service...
This is my code:
<script type="text/javascript>
$(document).ready(function () {
var endpointAddress = "http://localhost/SampleService/Service1.svc";
var url = endpointAddress + "/GetJson";
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
contentType: 'application/json',
data: "{}",
success: function (result) {
alert(result.length);
},
error:function(jqXHR)
{
alert(jqXHR.status);
}
});
});
</script>
You can see that I have accessed the service using both AJAX and getJSON methods.
However, when I try to display the data in an alert, it shows as undefined. I have tried using alert(result.d.length)
and
alert(result.d.GetEmployeeJSONResult)
, but they always show as undefined in both methods.
Below is the code for my WCF service:
namespace WcfServiceXmlAndJsonDemo
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method="GET",UriTemplate="GetXml",ResponseFormat=WebMessageFormat.Xml,RequestFormat=WebMessageFormat.Xml,BodyStyle=WebMessageBodyStyle.Bare)]
EmployeeXML GetEmployeeXML();
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetJson", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
List<EmployeeJSON> GetEmployeeJSON();
}
}
DataContract for EmployeeJSON:
namespace WcfServiceXmlAndJsonDemo
{
[DataContract]
public class EmployeeJSON
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public double Salary { get; set; }
}
}
Service1.svc.cs:
namespace WcfServiceXmlAndJsonDemo
{
public class Service1 : IService1
{
public List<EmployeeJSON> GetEmployeeJSON()
{
EmployeeJSON json = new EmployeeJSON()
{Name="Sumanth",Id=101,Salary=5000.00 };
return json;
}
}
}
Please assist me in resolving this issue.
Thank you for your help.
Krunal