如何传递JSON数据并转换为Web Service中的Object

时间:2011-10-28 04:50:23

标签: jquery asp.net ajax web-services

我希望能够转换在我的webservice中通过ajax(jquery)传递的JSON对象。目前我可以让它返回消息“Hello World”,但我不知道如何访问传递的JSON数据,然后转换为IList类型的集合,所以我可以迭代集合。我已经浏览过stackoverflow,但是我很困惑该怎么办可以帮助我。

这是我的代码:

jQuery的:

var data = { dvals: [{'Name' : 'Acer', 'Count' : '2'}, {'Name' : 'HP', 'Count' : '4'} ] };

function getProducts(json, pageIndex, pageSize) {
    json["PageIndex"] = pageIndex;
    json["PageSize"] = pageSize;

    $.ajax({
        type: 'POST',
        url: '/website2/WebServices/GetProducts.asmx/GetProductsAndFilters',
        data: JSON.stringify(json),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (responseText) {
            //alert(responseText.d);
            $('.console').html(responseText.d);
        },
        error: function (xhr, status, error) {
            //var msg = JSON.parse(xhr.responseText);
            //alert(msg.Message);
            $('.console').html(xhr.responseText)
        }
    });
}
getProducts(data, '0', '2');

我的asp.net C#:

public class Filter
{
    public string Name;
    public int Count;
}
public class Product
{
    public int Id;
    public string Title;
    public string ShortDescription;
    public string Brand;
    public string Model;
    public double SellPrice;
    public string DescountPercentage;
    public int Votes;
    public int TotalRating;
    public double Rating
    {
        get
        {
            return Votes / TotalRating;
        }
    }
}

public class FiltersAndProducts
{
    List<Filter> Filters;
    List<Product> Products;
    int PageIndex;
    int PageSize;
}

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

2 个答案:

答案 0 :(得分:3)

请注意在此处调用它的各种方法: http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

关于如何定义GetProductsAndFilters的内容。 您可以作为列表传递或作为DTO传递。

答案 1 :(得分:2)

如果你创建一个像

这样的课程
public class dvals{

public string Name{get;set;}
public string Count{get;set;}

}

准备json

var dvals =[{Name:'Acer',Count:'2'},{Name:'HP',Count:'4'}];
dval=JSON.stringify(dvals);

通过ajax发送

$.ajax({
        type: 'POST',
        url: '/website2/WebServices/GetProducts.asmx/GetProductsAndFilters',
        data: dval,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (responseText) {
            //alert(responseText.d);
              console.log(responseText);
            $('.console').html(responseText.d);
        },
        error: function (xhr, status, error) {
            //var msg = JSON.parse(xhr.responseText);
            //alert(msg.Message);
            $('.console').html(xhr.responseText)
        }
    });

webservice side

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetProductsAndFilters(IList<dvals> dvalsList)
{        
    return "Hello World";
}