I have an ActionResult with httpPost -attribute. If I'm not mistaken I need this attribute when the user are choosing a date from a DateTimePicker. In my case I have 2 Datetimepickers av type @html.EditorFor. These datepickers represent the DateTime properties StartDate and EndDate from my view model. These dates are suposed to be able for usage in the Controller and CreateGAStatisticsReport method after clicking "GAStatisticsReport-Submit" button as CreateGAStatisticsReport has the model as parameeter. However after I have chosen StartDate and EndDate nothing happens.

If I remove the HttpPost attribute from ActionResult GetData the method runs as expected except StartDate and EndDate will be Null. I don't know if the problem is model binding, HttpPost, html.BeginForm or the javascript logic for the submit button. Tried all kinds of things.

What am I missing here?

CreateGAStatisticsListModel:

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

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

GaStatisticsController (GetData is run when i click submitbutton):

 [HttpPost]
    public ActionResult GetData(GAStatisticsListModel model)
    {

        return Json(CreateGAStatisticsReport(model), JsonRequestBehavior.AllowGet);
    }


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


    public List<GAStatistics> CreateGAStatisticsReport(GAStatisticsListModel model)
    {

        var serviceAccountEmail = "xxxxxxxxxxxxxx@developer.gserviceaccount.com";
        var certificate = new X509Certificate2(@"C:\Users\user\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 = "Twist",
        });

        string start = model.StartDate.ToString(); //<----- The model date values are needed here
        model.StartDate = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture);

        string end = model.EndDate.ToString(); //<----- The model date values are needed here
        model.EndDate = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture);

        var request = GoogleAnalyticsService.Data.Ga.Get("ga:xxxxxxxx", start, end, "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;

    }

View (The problem might be here in the view, need to tell the button to store the dates choosen in the DateTimePickers so I can use them in the controller):

  @model GAStatisticsListModel

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

        <h2>Google Analytics Statistic Reports</h2>


    <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">Area Chart</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">Line Chart</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">Column Chart</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>
              <div id="chart_div4" style="width: 900px; height: 500px;"></div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>


    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="/Scripts/jquery.min.js"></script>
    <script type="text/javascript">


        //Submit button
        $('#GAStatisticsReport-Submit').click(function () {
            var grid = $('#GetData').data('tGrid');
            function onDataBinding(e) {
                var searchModel = {
                    StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
            };
            e.data = searchModel;
        }



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


        })
        google.load("visualization", "1", { packages: ["corechart"] });
        google.load("visualization", "1", { packages: ["treemap"] });
        function drawChart() {
            $.get('/GAStatistics/GetData', {},
                function (data) {
                    var tdata = new google.visualization.DataTable();

                    tdata.addColumn('date', 'Date');
                    tdata.addColumn('number', 'Visitors');

                    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 chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));

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

        }

    </script>
    }

Sorry for all the text. Anny help would be greatly appreciated.

有帮助吗?

解决方案

Using $.get( will issue an HttpGet request. The target in your code is '/GAStatistics/GetData' which is the action GetData in your GAStatistics controller. However, that method is marked with [HttpPost] and thus is not exposed to get requests.

Either use $.post( or mark the action with [HttpGet].

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top