Asp.net 我试图将一个由webservice生成的json文件传递给一个NVD3图形

Asp.net 我试图将一个由webservice生成的json文件传递给一个NVD3图形,asp.net,json,web-services,d3.js,nvd3.js,Asp.net,Json,Web Services,D3.js,Nvd3.js,我发布了一个类似的问题。我对ASP.NET和Web服务比较陌生。多亏了这个在线社区,我才能够尝试将我的Web服务链接到我的NVD3 stackArea图。当我首先保存json文件,然后在我的Web表单上使用它时,一切都正常。但是,我想把整个过程联系起来。我觉得我非常接近,非常感谢社区的反馈。这是我的网络表单: <!DOCTYPE html> <html> <head> <title></title> <link h

我发布了一个类似的问题。我对ASP.NET和Web服务比较陌生。多亏了这个在线社区,我才能够尝试将我的Web服务链接到我的NVD3 stackArea图。当我首先保存json文件,然后在我的Web表单上使用它时,一切都正常。但是,我想把整个过程联系起来。我觉得我非常接近,非常感谢社区的反馈。这是我的网络表单:

<!DOCTYPE html>

<html>
 <head>
  <title></title>
    <link href="css/nv.d3.css" rel="stylesheet" type="text/css">
    <link href="Content/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/pikaday.css" rel="stylesheet" type="text/css" />
    <link href="css/theme.css" rel="stylesheet" type="text/css" />
    <link href="css/site.css" rel="stylesheet" type="text/css" />
    <script src="scripts/Pikaday/moment.js" type="text/javascript"  ></script>
    <script src="scripts/Pikaday/pikaday.js" type="text/javascript"></script>
    <script src="scripts/jquery-1.9.1.js"></script>
    <script src="scripts/d3.min.js" charset="utf-8"></script>
    <script src="scripts/nv.d3.min.js"></script>

<style>
.singleLabel{
    min-height: 20px;
    text-align: left;
    font-size: large;
    margin-bottom:2px;
}
.textBox{
    border-left-width: 1px;
    min-height: 20px;
    text-align: center;
    font-size: large;
    margin-bottom:2px;
}
.textbox.dropDown{
    text-align: right;
}
text {
    font: 12px sans-serif;
}
html, body, #chart, svg{
    margin: 0 1px;
    height: 100%;
    width: 100%;
}
#chart{
       height: 70vh;
}

.nv-x text{
    font-size: 20px;
}
.nv-y text{
    font-size: 20px;
}
.nv-series text {
    font-size: 20px;
}
.row {
    font-size: 30px;
}
.column{

}
</style>
</head>

<body>
   <form id="form1" runat="server">
   <div class="row">&emsp;Report from:&emsp;
   <asp:TextBox ID="startDate" runat="server" columns="6" style="border:1px solid #ff0000"></asp:TextBox>
   &emsp;To&emsp;
   <asp:TextBox ID="endDate" runat="server" columns="6" style="border:1px solid #ff0000"></asp:TextBox>
   &emsp;<input type="button" id="btGO" value="Go!" />


   <%-- Date picker for start and end --%>
   <script = "text/javascript">
      var picker = new Pikaday({
           field: document.getElementById("startDate"),
           firstDay: 1,
           format: "YYYY-MM-DD",
           minDate: new Date('2000-01-01'),
           maxDate: new Date('2020-12-31'),
           yearRange: [2000,2020],
           numberOfMonths: 2
      });
   </script>

    <script = "text/javascript">
      var picker = new Pikaday({
           field: document.getElementById("endDate"),
           firstDay: 1,
           format: "YYYY-MM-DD",
           minDate: new Date('2000-01-01'),
           maxDate: new Date('2020-12-31'),
           yearRange: [2000,2020],
           numberOfMonths: 2
      });
   </script>
</div>
<div class="row">
<div class="col-lg-12">
<div id="chart">
    <svg></svg>
</div>
</div>
</div>
<script>
    <%--JQuery ensures that scripts run safely by waiting for all the required files to load first--%>
    $(document).ready(function () {
        $(document).on("click", "#btGO", function () {
            var startDate = $("#startDate").val();
            var endDate = $("#endDate").val();

            $.ajax({
                url: "dataWebService.asmx.cs/getTotalForDateInterval",
                data: {
                    startDate: startDate,
                    endDate: endDate
                },
                dataType: "json"
            }).done(function (data) {
                d3.json(data, function (error, data) {
                    nv.addGraph(function () {
                        var chart = nv.models.stackedAreaChart()
                                      .x(function (d) { return d[0] })
                                      .y(function (d) { return d[1] })
                                      .clipEdge(true)
                                      .useInteractiveGuideline(true);

                        chart._options.controlOptions = ['Expanded', 'Stacked'];

                        chart.xAxis
                            .showMaxMin(true)
                            .tickFormat(function (d) { return d3.time.format('%x')(new Date(d)) });

                        chart.yAxis
                            .tickFormat(d3.format(',.0f'));

                        d3.select('#chart svg')
                          .datum(data)
                            .transition().duration(500).call(chart);


                        nv.utils.windowResize(chart.update);

                        return chart;
                    });
                });
            });
        });
    });

</script>
</form>

</body>
</html>

.singleLabel{
最小高度:20px;
文本对齐:左对齐;
字体大小:大号;
边缘底部:2px;
}
.文本框{
左边框宽度:1px;
最小高度:20px;
文本对齐:居中;
字体大小:大号;
边缘底部:2px;
}
.textbox.dropDown{
文本对齐:右对齐;
}
正文{
字体:12px无衬线;
}
html、正文、图表、svg{
利润率:0.1px;
身高:100%;
宽度:100%;
}
#图表{
高度:70vh;
}
.nv-x文本{
字体大小:20px;
}
.nv-y文本{
字体大小:20px;
}
.nv系列文本{
字体大小:20px;
}
.行{
字体大小:30px;
}
.栏目{
}
&emsp;报告来源:&emsp;
&emsp;至&emsp;
&emsp;
var选择器=新皮卡日({
字段:document.getElementById(“startDate”),
第一天:1,
格式:“YYYY-MM-DD”,
新日期('2000-01-01'),
maxDate:新日期('2020-12-31'),
年份范围:[20002020],
月数:2
});
var选择器=新皮卡日({
字段:document.getElementById(“结束日期”),
第一天:1,
格式:“YYYY-MM-DD”,
新日期('2000-01-01'),
maxDate:新日期('2020-12-31'),
年份范围:[20002020],
月数:2
});
$(文档).ready(函数(){
$(文档)。在(“单击”上,“#btGO”,函数(){
var startDate=$(“#startDate”).val();
var endDate=$(“#endDate”).val();
$.ajax({
url:“dataWebService.asmx.cs/getTotalForDateInterval”,
数据:{
开始日期:开始日期,
结束日期:结束日期
},
数据类型:“json”
}).完成(功能(数据){
d3.json(数据,函数(错误,数据){
nv.addGraph(函数(){
var chart=nv.models.stackedAreaChart()
.x(函数(d){返回d[0]})
.y(函数(d){返回d[1]})
克利佩奇先生(对)
.useInteractiveGuideline(正确);
图表._options.controlOptions=[“扩展”、“堆叠”];
chart.xAxis
.showMaxMin(真)
.tickFormat(函数(d){返回d3.time.format('%x')(新日期(d))});
图1.yAxis
.tickFormat(d3.format(',.0f'));
d3.选择(“#图表svg”)
.基准(数据)
.transition().duration(500).调用(图表);
nv.utils.windowResize(图表更新);
收益表;
});
});
});
});
});
以下是我的Web服务:

 [WebMethod]
        public void getTotalForDateInterval(string startDate, string endDate)
        {
            string cs = ConfigurationManager.ConnectionStrings["vetDatabase_Wizard"].ConnectionString;
            List<keyValues> master = new List<keyValues>();

            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("sp_CountAndGroupByDate", con);
                cmd.CommandType = CommandType.StoredProcedure;

                //Linking SQL parameters with webmethod parameters
                SqlParameter param1 = new SqlParameter()
                {
                    ParameterName = "@startDate",
                    Value = startDate
                };

                SqlParameter param2 = new SqlParameter()
                {
                    ParameterName = "@endDate",
                    Value = endDate
                };

                cmd.Parameters.Add(param1);
                cmd.Parameters.Add(param2);
                con.Open();

                //Get time in milliseconds
                DateTime start = DateTime.ParseExact(startDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                DateTime end = DateTime.ParseExact(endDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                DateTime utime = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

                long startMilliseconds = (long)((start - utime).TotalMilliseconds);
                long endMilliseconds = (long)((end - utime).TotalMilliseconds);
                const long oneDayInMilliseconds = 86400000;

                //Declare temp dictionary to store the lists
                Dictionary<string, List<long[]>> temp = new Dictionary<string, List<long[]>>();
                string[] buildings = { "SSB", "GEN", "LYM", "LUD", "GCC", "MAC", "MMB" };

                //Create building lists and initialize them with individual days and the default value of 0 
                foreach (string building in buildings){
                    temp.Add(building, new List<long[]>());
                    for (long j = startMilliseconds; j <= endMilliseconds; j = j + oneDayInMilliseconds){
                        long[] timeTotal = { j, 0 };
                        temp[building].Add(timeTotal);
                    }
                }

                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {

                    //Remove time from dateTime2 and assign totals for appropriate date
                    string s = (rdr["dateOpened"].ToString()).Substring(0, 10);
                    DateTime dateOpened = DateTime.ParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                    long time = (long)((dateOpened - utime).TotalMilliseconds);
                    long total = (long)Convert.ToInt32(rdr["total"]);

                    string buildingName = rdr["building"].ToString();
                    int index = temp[buildingName].FindIndex(r => r[0].Equals(time));
                    temp[buildingName][index][1] = total;
                }
                    //add all the keyValue objects to master list
                    for (int i = 0; i < buildings.Length; i++)
                    {
                        keyValues kv = new keyValues();
                        kv.key = buildings[i];
                        kv.values = temp[kv.key];
                        master.Add(kv);
                    }

                JavaScriptSerializer js = new JavaScriptSerializer();

                //Serialize list object into a JSON array and write in into the response stream
                Context.Response.Write(js.Serialize(master));
            }
        }
[WebMethod]
public void getTotalForDateInterval(字符串startDate、字符串endDate)
{
字符串cs=ConfigurationManager.ConnectionString[“vetDatabase_向导”]。ConnectionString;
列表主机=新列表();
使用(SqlConnection con=newsqlconnection(cs))
{
SqlCommand cmd=新的SqlCommand(“sp_CountAndGroupByDate”,con);
cmd.CommandType=CommandType.storedProcess;
//将SQL参数与webmethod参数链接
SqlParameter param1=新的SqlParameter()
{
ParameterName=“@startDate”,
值=起始日期
};
SqlParameter param2=新的SqlParameter()
{
ParameterName=“@endDate”,
值=结束日期
};
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
con.Open();
//以毫秒为单位获取时间
DateTime start=DateTime.ParseExact(startDate,“yyyy-MM-dd”,System.Globalization.CultureInfo.InvariantCulture);
DateTime end=DateTime.ParseExact(endDate,“yyyy-MM-dd”,System.Globalization.CultureInfo.InvariantCulture);
DateTime utime=DateTime.ParseExact(“1970-01-01”,“yyyy-MM-dd”,System.Globalization.CultureInfo.InvariantCulture);
长启动毫秒=(长)((启动-utime).total毫秒);
long-endmillizes=(long)((end-utime.totalmillizes);
const long onedayin毫秒=86400000;
//声明临时字典以存储列表
Dictionary temp=新字典();
字符串[]建筑物={“SSB”、“GEN”、“LYM”、“LUD”、“GCC”、“MAC”、“MMB”};
//创建建筑列表,并使用单个天数和默认值0对其进行初始化
foreach(建筑物中的字符串建筑){
临时添加(建筑,新列表());
对于(长j=开始毫秒;jr[0]。等于(时间));
临时[建筑物名称][索引][1]=总数;
}
//将所有keyValue对象添加到主列表
对于(int i=0;i