从webservice返回列表

问题描述 投票:2回答:2

我正在使用Chartjs制作折线图,我从我的网络服务中收到错误。以下是该服务的代码:

[WebMethod]
    public List<object> getProgram12Months(string usersessionid)
    {
        List<object> iData = new List<object>();
        List<string> labels = new List<string>();

        //First get distinct Month Name for select Year.
        string query1 = "SELECT DISTINCT TOP (100) PERCENT TimeFrame FROM dbo.CSQ_ProgramCount12Months ORDER BY TimeFrame ";

        string conn = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
        SqlDataAdapter dap = new SqlDataAdapter(query1, conn);
        DataSet ds = new DataSet();
        dap.Fill(ds);
        DataTable dtLabels = ds.Tables[0];


        foreach (DataRow drow in dtLabels.Rows)
        {
            labels.Add(drow["TimeFrame"].ToString());
        }
        iData.Add(labels);

        return iData;
    }

当我从浏览器调用该方法时,我收到以下错误:

System.InvalidOperationException:生成XML文档时出错。 ---> System.InvalidOperationException:类型System.Collections.Generic.List`1 [[System.String,mscorlib,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]可能不会在此上下文中使用。

我的基础是off this

c# web-services chart.js
2个回答
2
投票

List不能序列化为web方法而不是这个你可以返回object []。

[WebMethod]
    public object[] getProgram12Months(string usersessionid)
    {
        List<object> iData = new List<object>();
        List<string> labels = new List<string>();

        //First get distinct Month Name for select Year.
        string query1 = "SELECT DISTINCT TOP (100) PERCENT TimeFrame FROM dbo.CSQ_ProgramCount12Months ORDER BY TimeFrame ";

        string conn = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
        SqlDataAdapter dap = new SqlDataAdapter(query1, conn);
        DataSet ds = new DataSet();
        dap.Fill(ds);
        DataTable dtLabels = ds.Tables[0];


        foreach (DataRow drow in dtLabels.Rows)
        {
            labels.Add(drow["TimeFrame"].ToString());
        }
        iData.Add(labels.ToArray());

        return iData.ToArray();
    }

2
投票

我通过创建两个填充它们的类来解决这个问题。谢谢你,你的帖子帮助我指引正确的方向。

public class ChartData2
    {
        public List<string> Legends;
        public List<int> AD;


    }

    public class Legend
    {
        public List<string> Months;
    }
© www.soinside.com 2019 - 2024. All rights reserved.