我正在构建一个ASP.NET应用程序,用于查询我的SQL Server并使用NVD3.js显示svg图。我的Web方法生成正确的JSON文件,当我单独加载它时(即sampleJSON3.json)。现在,我试图将json文件直接传递到我的应用程序,但不知道该怎么做。我非常感谢社区的反馈。谢谢!
这是我的网络方法:
[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));
}
}
以下是我的网络表单的一部分:
<script>
d3.json('sampleData3.json', 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>
答案 0 :(得分:0)
将以下属性添加到您的网络方法会将结果转换为JSON
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<keyValues> getTotalForDateInterval(string startDate, string endDate)
{
return master;
}
您也可以使用Ajax来调用您的方法,而不是将其存储在文件中。
$.ajax({
url:"url/toController/method"
}).done(
function(data){
d3.json(data);
})
.fail() //if you'd like to add an error fix or notification if your call failed