【问题标题】:How can I Return a Partial view depending on Controller within current page如何根据当前页面中的控制器返回部分视图
【发布时间】:2013-07-01 15:39:32
【问题描述】:

如何根据控制器渲染局部视图?

所以..我需要根据已发布的值呈现部分视图:

  <script type="text/javascript" language="javascript">
      $(document).ready(function () {
                            $("#GetReport").click(function () {
                                $("form[name=StatsForm]").submit();

                            });
                        });
  </script>



<% Html.RenderPartial("InterStats"); %> //this is wrong i need it to render the partial depending on selection and only after the  $("#GetReport").click

控制器:

 /// <summary>
        /// POST /Stats/Index
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection form)
        {
            // Deal with the form 
            var manufacturerId = Convert.ToInt32(form["manufacturerId"]);
            var reportId = Convert.ToInt32(form["reportId"]);
            var categoryId = Convert.ToInt32(form["categoryId"]);
            var retailerId = Convert.ToInt32(form["retailerId"]);
            var countryId = Convert.ToInt32(form["countryId"]);
            var regionId = Convert.ToInt32(form["regionId"]);
            var manufacturerWidgetId = (form["ManufacturerWidgetId"]);
            var startDate = new DateTime(1, 1, 1, 0, 0, 0, 0);
            var endDate = new DateTime(1, 1, 1, 0, 0, 0, 0);    

            var reportName = _reportRepository.GetReport(reportId);


            switch (reportName.Code)
            {
                case "INTER":
                    return RedirectToAction("InterStats",
                                        new
                                        {
                                            manufacturerId = manufacturerId,
                                            countryId = countryId,
                                            startDate = "2013-01-01",
                                            endDate = "2013-01-31"

                                        });
                    break;
                case "CUMLEADS":
                    return RedirectToAction("LeadStats",
                                        new
                                        {
                                            manufacturerId = manufacturerId,
                                            countryId = countryId,
                                            categoryId = categoryId,
                                            startDate = startDate.ToString("yyyy-MM-dd"),
                                            endDate = endDate.ToString("yyyy-MM-dd")
                                        });
                    break;
                case "IMP":

                    break;
            }

            return View();


        }




    /// </summary>
    /// <returns></returns>
    /// [JsonpFilter]
    [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
    public ActionResult InterStats(int manufacturerId, int countryId, DateTime startDate, DateTime endDate)
    {

        //Get all manufacturerwidgets for manufacturer
        var manufacturerWidget = _manufacturerWidgetsRepository.GetManufacturerWidgetByManufacturerAndCountry(manufacturerId, countryId);
        var interReportJson = new InterReportJson();
        var interRecordList = new List<InterRecord>(); // a list of my anonymous type without the relationships
        interReportJson.InterRecordList = new List<InterRecord>();
        var count = 1;
        foreach (var mw in manufacturerWidget)
        {
            var widgetName = mw.Description;

            //Get the product stats data
            var imps = _productStatsRepository.GetSumImpressionsProductStatsForManufacturerCountryDate(
                mw.Id, countryId, startDate, endDate);


            var clicks = _productStatsRepository.GetSumClicksProductStatsForManufacturerCountryDate(
                mw.Id, countryId, startDate, endDate);

            float ctr = 0;
            if (imps != 0 && clicks != 0)
            {
                ctr = ((clicks / (float)imps) * 100);
            }



            //  Create the data for the report
            var interRecord = new InterRecord
            {
                WidgetName = widgetName,
                Impressions = imps,
                Interactions = clicks,
                Ctr = ctr,
                Count = count
            };




           interReportJson.InterRecordList.Add(interRecord);

            count++;
        }

        interReportJson.Counter = count;




        return PartialView(interReportJson);
    }

目前没有 我的部分正在一个新窗口中打开,并且它失败了,因为在提交表单之前没有数据。而且它可能不是部分“InterStats”,它可能是部分“LeadsStats”

编辑

我正在使用 AJAX 执行以下操作:

 <script type="text/javascript">

            $("#GetReport").click(function () {


                var manufacturerId = $("#manufacturerId > option:selected").attr("value");
                var countryId = $("#countryId > option:selected").attr("value");
                var startDate = $("#startDate").val();
                var endDate = $("#endDate").val();

                //var manufacturerId = 241;
                //var countryId = 230;
                //                 var startDate = '2013-01-01';
                //                 var endDate = '2013-01-31';

                var theUrl = "/ProductStats/Parameters/" + manufacturerId + "/" + countryId + "/" + startDate + "/" + endDate;

                alert(theUrl);

                $.ajax({
                    type: "POST",
                    //contentType: "application/json; charset=utf-8",
                    url: theUrl,
                    data: { 'manufacturerId': manufacturerId, 'countryId': countryId, 'startDate': startDate, 'endDate': endDate },
                    dataType: "json",
                    success: function (data) {


                        //see this http://stackoverflow.com/questions/11472947/how-to-format-my-json-data-for-stack-column-chart-in-highcharts


                        var widgetNameArray = [];

                        var impressionsArray = [];

                        var intsArray = [];

                        for (var i = 0; i < data.length; i++) {

                            var item1 = data[i];
                            //only display on graph if not 0
                            if (item1.Impressions > 0) {


                                var widgetCategories = item1.WidgetName;

                                //put into an array
                                widgetNameArray.push(widgetCategories);

                                var imps = item1.Impressions;

                                impressionsArray.push(imps);

                                var ints = item1.Interactions;
                                intsArray.push(ints);
                            }
                        }


                        // Create the chart
                        $('#container').highcharts({
                            chart: {
                                type: 'column'
                            },
                            title: {
                                text: 'Inter Chart ' + startDate + ' to ' + endDate
                            },
                            xAxis: {
                                categories: widgetNameArray,
                                labels: {
                                    rotation: -45,
                                    align: 'right',
                                    style: {
                                        fontSize: '13px',
                                        fontFamily: 'Verdana, sans-serif'
                                    }
                                }
                            },
                            yAxis: {
                                min: 0,
                                title: {
                                    text: 'Impressions/Interactions'
                                },
                                stackLabels: {
                                    enabled: false,
                                    style: {
                                        fontWeight: 'bold',
                                        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                                    }
                                }
                            },
                            legend: {
                                align: 'right',
                                x: -100,
                                verticalAlign: 'top',
                                y: 20,
                                floating: true,
                                backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
                                borderColor: '#CCC',
                                borderWidth: 1,
                                shadow: false
                            },
                            tooltip: {
                                formatter: function () {
                                    return '<b>' + this.x + '</b><br/>' +
                        this.series.name + ': ' + this.y + '<br/>';
                                }
                            },
                            plotOptions: {
                                bar: {
                                    dataLabels: {
                                        enabled: true
                                    }
                                }
                            },
                            series: [{
                                name: 'Impressions',
                                data: impressionsArray
                            }, {
                                name: 'Interactions',
                                data: intsArray
                            }]
                        });




                        var table = document.getElementById("usertable");
                        var tabledata = "";

                        tabledata += "<tr>";
                        tabledata += "<th>Widget Name</th>";
                        tabledata += "<th>Impressions</th>";
                        tabledata += "<th>Interactions</th>";
                        tabledata += "<th>CTR</th>";
                        tabledata += "</tr>";



                        for (var i = 0; i < data.length; i++) {

                            var item = data[i];

                            tabledata += "<tr>";
                            tabledata += "<td>" + item.WidgetName + "</td>";
                            tabledata += "<td>" + item.Impressions + "</td>";
                            tabledata += "<td>" + item.Interactions + "</td>";
                            tabledata += "<td>" + item.Ctr.toFixed(2) + "%</td>";
                            tabledata += "</tr>";

                        }


                        table.innerHTML = tabledata;

                        $("th").css("background-color", "#3399FF");
                        $("tr:even").css("background-color", "#eeeeee");
                        $("tr:odd").css("background-color", "#ffffff");


                    }
                }
                 );


            });

        </script>

但这仅适用于其中一个报告,因为表格/chrt 的格式因报告而异,因此需要根据报告 ID 分开显示它们的方式。

我希望很清楚我需要做什么,如果没有,请询​​问。

谢谢!

【问题讨论】:

  • 那么...有什么问题?你已经展示了很多代码,但我不知道你在问什么,你在哪里挣扎。同样,您已经展示了您尝试过的内容,但没有展示您遇到的问题。也许考虑让你的问题更清楚。

标签: c# jquery asp.net-mvc-3 partial-views


【解决方案1】:

您需要调用 AJAX 方法并传入必要的数据,以便它能够完成您想要的响应。您可以执行 GET 或 POST。在 GET 上,在查询字符串上放置键值对,在 POST 正文中放置键值对。您可以查看 jQuery AJAX 文档。 看起来您必须执行 AJAX 或回发才能使您的代码正常工作,因为它需要用户输入。

我建议类似...

<div id="reportDiv">
   <!-- dynamic content will be populated here after user makes some selection, etc.. -->
</div>

<script type="text/javascript">
   $(document).ready(function () {
      $("#GetReport").click(function () {
         if (selectionDictatesThatReportBeShown) {
            // Make AJAX call and put response html in the reportDiv
            $('#reportDiv').load('/SomeController/SomeAction?key1=value1&key2=value2');
         }

         // optionally do this?
         $("form[name=StatsForm]").submit();
      });
   });
</script>

【讨论】:

    【解决方案2】:

    感谢 Sam 的意见,很抱歉不清楚我需要做什么。

    我实际上想根据用户从下拉列表中选择的报告来选择部分视图。

    所以在视图中我使用了 .change 以便我们知道何时选择了报告:

    <script type="text/javascript">
            //<![CDATA[
    
         $(function () {
    
             $("#selectReport").hide();
             var manufacturerId;
    
             $("select#manufacturerId").change(function () {
                 manufacturerId = $("#manufacturerId > option:selected").attr("value");
                 $("#selectReport").show();
    
             });
    
    
             $("select#reportId").change(function () {
                 var reportId = $("#reportId > option:selected").attr("value");
    
                 var theUrl = "/ReportStats/GetReport/" + reportId + "/" + manufacturerId;
    
                 $.ajax({
                     url: theUrl,
                     success: function (data) {
                         $('#ajaxOptionalFields').html(data);
                     },
                     error: function () {
                         alert("an error occured here");
                     }
                 });
             });
         });
    
            //]]>
        </script>
    

    在控制器中我放了一个案例陈述,这样我就知道我在哪个报告上:

    //这里我们决定哪个部分将被看到哪个报告(所以哪个ajax调用将被触发......

     switch (report.Code)
                {
                    case "INTER":
                        ViewData["InterStats"] = true;
                        break;
                    case "CUMLEADS":
                        ViewData["CumLeadsStats"] = true;
                        break;
                }
    

    在视图中,我使用了一个 if 语句来决定显示哪个报告部分:

    <% if (Convert.ToBoolean(ViewData["InterStats"]))
       { %>
    <% Html.RenderPartial("InterReport"); %>
    <% }
       else if (Convert.ToBoolean(ViewData["CumLeadsStats"]))
       { %>
    <% Html.RenderPartial("CummulativeReport"); %>
    <% }  %>
    

    我不确定这是否是一种非常糟糕的方式来做我需要的事情,但它似乎有效。

    【讨论】:

    • 看来你已经把事情弄清楚了,干得好!至于您可能尝试过的替代方法 - 可能对单独的报告有单独的视图,并且控制器选择不同的视图。我没有投反对票,而且网站上的礼仪是当你发表评论时发表评论,所以没有人发表评论太糟糕了。如果可能,您应该将您的答案标记为正确的答案,这样人们就不会继续访问此页面来回答您的问题。
    猜你喜欢
    • 2012-11-07
    • 2012-12-02
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多