如何在执行按钮后加载JQuery函数?

时间:2014-03-25 11:39:39

标签: c# jquery ajax asp.net-mvc razor

我是JQuery的新手并且被困在了。我有一个MVC应用程序从Google API绘制图表。我正在开发一个UI,它允许用户从DropDownList中选择一个项目,单击Run并加载图表。我目前的问题是当我去视图时图表是直接运行的。绘制图表的JQuery函数在GAStatisticsController中实现了GetData ActionResult。

我有一个dropDownList,包含模型类和按钮中的可选项(“GAStatisticsReport-Submit”)。我只需要检查DropDownList中是否选择了“访客”项,如果是这样的话,我可以点击运行,图表将显示访问者的数据。我怎么能归档这个?

控制器有一个名为CreateGAStatisticsReport的方法,它将数据返回到视图以供显示的图表。此方法具有ActionResult。但是,当函数绘制图表时,它会从GetData ActionResult而不是GAStatistics中绘制它们。

以下是观点:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.load("visualization", "1", { packages: ["treemap"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        $.get('/GAStatistics/GetData', {}, <--- here's GetData ActionResult in the Controller
            function (data) {
                var tdata = new google.visualization.DataTable();

                tdata.addColumn('date', 'Datum');
                tdata.addColumn('number', 'Besökare');

                for (var i = 0; i < data.length; i++) {
                    var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
                    tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
                }

                var options = {
                    title: "Number of unique visitors"
                };

                var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
                var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
                var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));

                chart1.draw(tdata, options);
                chart2.draw(tdata, options);
                chart4.draw(tdata, options);
            });
    }

</script>

<table class="adminContent">
         <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GAStatisticsId ):
            </td>
            <td class="adminData">
                @Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
                <input type="button" id="GAStatisticsReport-Submit" class="t-button" value="@T("Run")" />
        </tr>
</table>

我的ViewModel(注意:当选择SelectListItem“访问者并且用户点击了”运行“按钮时,它应该执行并绘制图表):

    public class GAStatisticsListModel : BaseNopModel
    {
        public GAStatisticsListModel()
        {
            AvailableGAStatistics = new List<SelectListItem>();

            SelectListItem Visitors = new SelectListItem() { Text = "Besökare", Value = "1", Selected = false };
            SelectListItem PercentNewVisitors = new SelectListItem() { Text = "Nya Besökare (Procent)", Value = "2", Selected = false };
            SelectListItem ConversionRate = new SelectListItem() { Text = "Konverteringsgrad", Value = "3", Selected = false };



            AvailableGAStatistics.Add(Visitors);
            AvailableGAStatistics.Add(PercentNewVisitors);
            AvailableGAStatistics.Add(ConversionRate);
        }


        [NopResourceDisplayName("Admin.ShopStatistics.List.StartDate")]
        [UIHint("DateNullable")]
        public DateTime? StartDate { get; set; }

        [NopResourceDisplayName("Admin.ShopStatistics.List.EndDate")]
        [UIHint("DateNullable")]
        public DateTime? EndDate { get; set; }

         [NopResourceDisplayName("Admin.GAStatistics.GAStatistics.GAStatisticsList")]
        public int GAStatisticsId { get; set; }

        public List<SelectListItem> AvailableGAStatistics { get; set; }

    }
}

Controller(GetData将数据传递给CreateGAStatisticsReport视图中的JQuery代码,以显示图表):

public class GAStatisticsController : Controller
    {

        //GET: /ShopStatistics/
        [HttpPost]
        public ActionResult GetData() 
        {
            return Json(CreateGAStatisticsReport(), JsonRequestBehavior.AllowGet);
        }



        public ActionResult GAStatistics()
        {
            return View(new GAStatisticsListModel());
        }


        private List<GAStatistics> CreateGAStatisticsReport()
        {

            var serviceAccountEmail = "xxxxxxxxx@developer.gserviceaccount.com";
            var certificate = new X509Certificate2(@"C:\Users\Desktop\NopCommerce\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);


            var credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));

            // Create the service.
            //Twistandtango
            var GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "MyApp",
            });

            var request = GoogleAnalyticsService.Data.Ga.Get("ga:xxxxxxxx", "2014-01-24", "2014-01-30", "ga:visitors");
            //Specify some addition query parameters
            request.Dimensions = "ga:date";
            request.Sort = "-ga:date";
            request.MaxResults = 10000;

            //Execute and fetch the results of our query
            Google.Apis.Analytics.v3.Data.GaData d = request.Execute();


            List<GAStatistics> ListGaVisitors = new List<GAStatistics>();

            foreach (var row in d.Rows)
            {

                GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
                ListGaVisitors.Add(GaVisits);

            }


            return ListGaVisitors;

        }
    }

1 个答案:

答案 0 :(得分:1)

对于你想要的你不能使用google.setOnLoadCallback(drawChart)(参见this link也明白为什么)。如果我理解你想要做什么,你必须在你的按钮上设置一个事件,该事件将执行drawChart()函数。

像这样:

$("#GAStatisticsReport-Submit").click(function(){ drawChart() })

因此,当您点击该按钮时,图表将被绘制。 要仅在选择“访客”时绘制图表,您必须执行以下操作:

$("#GAStatisticsReport-Submit").click(function(){ 
    if($("select[name='GAStatisticsId'] option:selected").text()=="Visitors")
        drawChart() 
})