【问题标题】:How can I call my webmethod in my ASP.NET app in c#?如何在 c# 中的 ASP.NET 应用程序中调用我的 webmethod?
【发布时间】:2016-07-09 19:46:29
【问题描述】:

我正在构建一个 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>

【问题讨论】:

    标签: c# asp.net json web-services webforms


    【解决方案1】:

    将以下属性添加到您的 Web 方法中会将结果转换为 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
    

    【讨论】:

    • 非常感谢!我添加了您建议的功能,但我一定犯了一个明显的错误。我用你的修改发了一个新帖子:stackoverflow.com/questions/38337383/…我想知道你是否可以看看它。非常感谢您的帮助和时间!
    猜你喜欢
    • 2013-10-07
    • 1970-01-01
    • 2011-08-04
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    相关资源
    最近更新 更多