tags:

views:

292

answers:

3

Hi,

I have the piece of code below of a template Ajax enabled WCF service. What can i do to make it return JSon instead of XML? thanks.

using System; 
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

[ServiceContract(Namespace = "WCFServiceEight")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CostService
{
    // Add [WebGet] attribute to use HTTP GET
    [OperationContract]
    [WebGet]
    public double CostOfSandwiches(int quantity)
    {
        return 1.25 * quantity;
    }
}
+1  A: 

Have you tried:

[WebGet(ResponseFormat= WebMessageFormat.Json)]
tomasr
thanks.Yes i tried but i still get error from the JQuery code. here is the code i am using to call the service: var parameters = 7 $.ajax({ type: "POST", url: "http://localhost:53153/TestWebServiceEightSite/CostService.svc", data: parameters, contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { $("InputHTML").val(result); }, error: function(e) { alert(e); }});
Zinoo
Have you looked at: http://www.west-wind.com/weblog/posts/324917.aspx ?
tomasr
+1  A: 

These articles helped me get it working:

jQuery AJAX calls to a WCF REST Service

Passing a JSON object to a WCF service with jQuery

Toji
They are very informative. thank you.
Zinoo
A: 

If you want to use the POST verb as in $.ajax({ type: "POST", ...) you will need to markup your method with [WebInvoke(Method="POST"].

Since you marked it up with [WebGet] (which is equivalent to [WebInvoke(Method="GET")]) you should call the service using the GET verb, e.g.:

$.ajax({ type: "GET", ...) or use $.get(url, data, ...) (see jQuery.get for more info).

And you'll need to set the ResponseFormat to Json, as tomasr already pointed out.

Oliver