2016-07-09 3 views
0

私はSQL Serverを照会し、NVD3.jsを使ってsvgグラフを表示するASP.NETアプリケーションを構築しています。私のWebメソッドは、個別にロードするときに動作する正しいJSONファイル(つまり、sampleJSON3.json)を生成します。今、私は直接私のアプリにjsonファイルを渡そうとしているが、それを行う方法を知らない。私はコミュニティの感謝を大いに感謝します。ありがとうございました!ここで私のASP.NETアプリケーションでC#でWebメソッドを呼び出すにはどうすればよいですか?

は、私の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)); 
    } 
} 

は、私のWebフォームの一部です:

<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

ウェブメソッドに以下の属性が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 
+0

ありがとうございました!私はあなたの提案された機能を追加しましたが、私は明らかな間違いをしているに違いありません。あなたの変更を加えて新しい投稿を作成しました:http://stackoverflow.com/questions/38337383/i-am-trying-to-pass-a-json-file-generated-with-a-webservice-to-an-nvd3 -graph私はあなたがそれを見てくださいことができるかどうか疑問に思っていた。私はあなたの助けと時間を大変感謝しています! – Johnathan

関連する問題