hguser
hguser

Reputation: 36028

Returning json in asp.net webservice

In my application,we use the prototype1.4.2 in the page.

And we need the tree view which support lazy load(make a ajax request and add the data from the server to the node),then I found the

TafelTree

It is built based on the prototype.

And there is a function:

onopenpopulate:

It will load data from the server according the "openlink" provided by user.

Called after a branch is opened. When it's open, it launch an Ajax request at the page openlink and send the Ajax response to the user function. It must return a JSON string representing an array of one or more TafelTreeBranch. Override setOnOpenPopulate() of TafelTree

But it need the server return pure json data format.

And I have created a webservice this way:

[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService {
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string loadData(id) {
      //some logic according the id
      return "{id:0,name:'xx'}";
    }
}

However when I invoke this service use:

http://xxx/UtilService/loadData?id=0

I always get the xml format.

Through google,it seems that I have to set the "content-type" when make the ajax request.

However,in my case,the ajax is sent by the "TafelTree",I can not add extra parameters.

Any idea? or use another prototype based tree?

Upvotes: 0

Views: 1656

Answers (1)

Ghyath Serhal
Ghyath Serhal

Reputation: 7632

you can use jquery to do an Ajax call.

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "webServiceUrl/MethodName",
        data: "{Id: '" + id + "'}",
        dataType: "json",
        success: loadSucceeded,
        error: loadFailed,
        async: true
    });

function loadSucceeded(result, status)
{
    var data = result.d;
}

function loadFailed(result, status)
{
}

Note that it is not necessarily to return a string, you can return a list of object.

[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService 
{
    [WebMethod]
    public List<string> loadData(id) {
      //some logic according the id
      return new List<string>(){"data"};
    }
}

Upvotes: 1

Related Questions