将“剃刀视图”按钮连接到控制器操作方法

时间:2014-03-21 12:36:38

标签: c# javascript asp.net .net razorengine

我有一个控制器和一个名为“CreateGAStatisticsReport”的方法,它返回一个包含谷歌分析数据的列表。在控制器中我还有两个ActionResults,“GaStatistics”返回一个“ListModel”,用于向视图添加控件,“GetData”返回“CreateGAStatisticsReport”中的数据到视图。

在视图中,我有一些从Google Charts API中绘制图表的Javascript,我也有一些当前没有使用过的控件,而且DropDownList中包含一些可选项。

我想知道如何将按钮连接到方法“”CreateGAStatisticsReport“”,我只想在用户点击按钮后运行并加载报表/图表。香港专业教育学院尝试使用[HttpPost],我也为按钮做了一些Javascript但我无法让它工作。我该如何处理?

控制器:

[AdminAuthorize]
    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.
            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;

        }
    }

查看:

    @model GAStatisticsListModel

@using Nop.Admin.Models.GAStatistics;
@using Telerik.Web.Mvc.UI;
@using Nop.Admin.Controllers;
@using System.Web.Mvc.Html;
@{
    ViewBag.Title = "GAStatistics";
    Layout = "~/Administration/Views/Shared/_AdminLayout.cshtml";
}



<h2>Google Analytics statistics</h2>


<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', {},
            function (data) {
                var tdata = new google.visualization.DataTable();

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


                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: "Antal unika besökare per datum"
                };

                var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));

                var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));

                //var chart3 = new google.visualization.PieChart(document.getElementById('chart_div3'));

                var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));


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



    $(function () {
        $('GAStatisticsReport-Submit').click(function () {
            $.post("@Url.Action("GetData","GAStatistics")");
     });
   });


</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("Admin.Common.Search")" />
        </tr>
</table>

<div class="t-widget t-grid">
  <table cellspacing="0">
    <thead class="t-grid-header">
      <tr>
        <th class="t-header" scope="col">
          <span class="t-link">Yt-Diagram</span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div id="chart_div1" style="width: 900px; height: 500px;"></div>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="t-widget t-grid">
  <table cellspacing="0">
    <thead class="t-grid-header">
      <tr>
        <th class="t-header" scope="col">
          <span class="t-link">Linje-Diagram</span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div id="chart_div2" style="width: 900px; height: 500px;">
    </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<div class="t-widget t-grid">
  <table cellspacing="0">
    <thead class="t-grid-header">
      <tr>
        <th class="t-header" scope="col">
          <span class="t-link">Stapel-diagram</span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div id="chart_div4" style="width: 900px; height: 500px;">
    </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>

1 个答案:

答案 0 :(得分:0)

  1. 您无法将private方法称为MVC中的操作
  2. 您应该返回MVC支持的ViewResult
  3. 您只需要调用GetData动作即可为您执行所有操作,但请删除JsonRequestBehavior.AllowGet,因为您使用[HttpPost]

    进行修饰

    确保您提出POST请求