views:

4407

answers:

5

I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.

Webservice Code

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
    return "Hello World!";
}

I also have these attributes assigned to the class

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]

jQuery Code

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "ScheduleComputerDS.asmx/HelloWorld",
    data: "{}",
    dataType: "jsonp",
    success: function(data) {
        alert(data);
    }
});

The ASMX page always returns as content type "text/xml". Anything I'm missing?

EDITS: In response to a couple answers:

If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.

My class does inherit from "System.Web.Services.WebService".

From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.

Thanks for all your help!

+1  A: 

Have you tried with datatype json?

Also, have a look at Encosia's Using jQuery to Consume ASP.NET JSON Web Services article on the matter. There's some good info on common pitfalls too.

Russ Cam
+2  A: 

I think there's a typo:

dataType: "jsonp",

Should be:

dataType: "json",
eduncan911
awesome :) i made this mistake recently but i had "script" in there. was copied and pasted from an example
Simon_Weaver
Ah, no +1 then? lol
eduncan911
+2  A: 

Rich Strahl has a really basic post that should help you out with this.

http://www.west-wind.com/weblog/posts/164419.aspx

bendewey
This link was very helpful. Thank you
TheDude
+2  A: 

As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.

You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET.

Rob Windsor
A: 

On the asmx page you have to add ContentType="application/json" to the Page directive.

Example:

<%@ WebService Language="C#" CodeBehind="Service.asmx.cs" Class="Application.Service" ContentType="application/json" %>
Jesse Dearing