在asp.net webservice中返回json

Returning json in asp.net webservice

本文关键字:返回 json webservice asp net      更新时间:2023-09-26

在我的应用程序中,我们在页面中使用了prototype1.4.2。

我们需要支持延迟加载的树视图(发出ajax请求并将数据从服务器添加到节点),然后我找到了

TafelTree

它是在原型的基础上建造的。

还有一个函数:

onopenpopulate:

根据用户提供的"openlink"从服务器加载数据。

分支机构开通后调用。当它打开时,它启动一个Ajax在页面打开链接处请求,并将Ajax响应发送给用户函数。它必须返回一个JSON字符串,表示一个或更多的TafelTreeBranch。重写TafelTree的setOnOpenPopulate()

但是它需要服务器返回纯json数据格式。

我已经这样创建了一个webservice:

[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'}";
    }
}

但是当我调用这个服务时使用:

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

我总是得到xml格式。

通过谷歌,似乎我必须设置"内容类型"时,使ajax请求。

然而,在我的情况下,ajax是由"TafelTree"发送的,我不能添加额外的参数。

任何想法?或者使用另一个基于原型的树?

你可以使用jquery来做一个Ajax调用。

$.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)
{
}

注意,不一定要返回一个字符串,可以返回一个对象列表。

[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"};
    }
}