简体   繁体   中英

How to load a JQuery function after execute with button?

I'm kinda new at JQuery and are stuck atm. I have an MVC application that draws charts from Google API. I'm working on a UI that alows the user to select a item from a DropDownList, click Run and the charts will load. My current problem is the charts are run directly when i go to the view. The JQuery function that draws the charts implements the GetData ActionResult in GAStatisticsController.

I have a dropDownList with selectable items from a model class and a button ("GAStatisticsReport-Submit"). I just need t check if item "Visitors" is selected in the DropDownList, if that's the case i can click run and the Charts will display the data with visitors. How could i archive this?

The controller has a method called CreateGAStatisticsReport wich returns data to the view for the charts to display. This method has an ActionResult. However when the function draws the charts it draws them from GetData ActionResult and not GAStatistics.

Here is the view:

<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>

My ViewModel (note: When SelectListItem "Visitors is selected and the user has clicked the "Run" button it should execute and draw the charts):

    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; }

    }
}

The Controller (GetData passes data to the JQuery code in the view from CreateGAStatisticsReport for the charts to display):

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;

        }
    }

For what you want you can't use google.setOnLoadCallback(drawChart) (see this link too understand why). If I understand what you want to do, you must set a event on your button and that event will execute the drawChart() function.

Like this:

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

So, when you click on that button the chart will be draw. To draw the chart only if the 'Visitors' is selected you must do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM