问题
I have posted a similar question. I am relatively new to ASP.NET and webservices. Thanks to the online community, I was able to attempt linking my webservice to my NVD3 stackArea graph. Everything works when I first save the json file then use it on my webform. However, I want to link the entire process. I feel that I am very close and would greatly appreciate the community's feedback. Here is my webform:
<!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"> Report from: 
<asp:TextBox ID="startDate" runat="server" columns="6" style="border:1px solid #ff0000"></asp:TextBox>
 To 
<asp:TextBox ID="endDate" runat="server" columns="6" style="border:1px solid #ff0000"></asp:TextBox>
 <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>
Here is my webservice:
[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));
}
}
来源:https://stackoverflow.com/questions/38337383/i-am-trying-to-pass-a-json-file-generated-with-a-webservice-to-an-nvd3-graph