【问题标题】:HttpPost not executingHttpPost 未执行
【发布时间】:2014-05-11 10:20:53
【问题描述】:

我有一个带有 httpPost 属性的 ActionResult。如果我没记错的话,当用户从 DateTimePicker 中选择日期时,我需要这个属性。就我而言,我有 2 个 Datetimepickers av 类型 @html.EditorFor。这些日期选择器代表我的视图模型中的 DateTime 属性 StartDate 和 EndDate。在单击“GAStatisticsReport-Submit”按钮后,这些日期应该能够在 Controller 和 CreateGAStatisticsReport 方法中使用,因为 CreateGAStatisticsReport 将模型作为参数。但是,在我选择了 StartDate 和 EndDate 之后,什么也没有发生。

如果我从 ActionResult GetData 中删除 HttpPost 属性,则该方法将按预期运行,但 StartDate 和 EndDate 将为 Null。我不知道问题是模型绑定、HttpPost、html.BeginForm 还是提交按钮的 javascript 逻辑。尝试了各种方法。

我在这里缺少什么?

创建GAStatisticsListModel:

[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):

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

    }

视图(问题可能出在视图中,需要告诉按钮存储在 DateTimePickers 中选择的日期,以便我可以在控制器中使用它们):

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

对不起所有的文字。任何帮助将不胜感激。

【问题讨论】:

    标签: c# jquery asp.net-mvc datepicker viewmodel


    【解决方案1】:

    使用$.get( 将发出HttpGet 请求。代码中的目标是'/GAStatistics/GetData',它是 GAStatistics 控制器中的操作 GetData。但是,该方法标有[HttpPost],因此不会公开获取请求。

    使用$.post( 或使用[HttpGet] 标记操作。

    【讨论】:

    • 谢谢,我现在可以执行按钮了。但是,在我选择日期并单击提交之后,HttpPost 属性似乎没有像 model.StartDate 和 model.EndDate 那样用任何 DateTime 值填充。我只是得到空
    猜你喜欢
    • 2021-09-14
    • 2015-06-04
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    相关资源
    最近更新 更多