简体   繁体   English

如何根据当前页面中的控制器返回部分视图

[英]How can I Return a Partial view depending on Controller within current page

How do I render a partial view depending on the controller? 如何根据控制器渲染局部视图?

So..I need to render a partial view depending on the values that have been posted: 所以..我需要根据已发布的值来渲染局部视图:

  <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

Controller: 控制器:

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

At the moment without the <% Html.RenderPartial("InterStats"); 目前没有<%Html.RenderPartial(“ InterStats”); %> my partial is opening in a new window and with it its failing as there is no data untill after the form has been submitted. %>我的零件正在新窗口中打开,由于没有数据,直到提交表单后才出现数据。 and also It might not be partial "InterStats" it could be partial "LeadsStats" 并且也可能不是部分“ InterStats”,也可能是部分“ LeadsStats”

Edit 编辑

I was doing the following with AJAX: 我正在使用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>

But this only work for one of the report as the format of the table/chrt varies depending on the report so i nned to seperate how to display them depending on the report id. 但这仅适用于报告之一,因为表/ chrt的格式根据报告而有所不同,因此请根据报告ID区分如何显示它们。

I hope it is clear what I need to do please ask if not. 我希望很清楚我需要做什么,请问是否可以。

Thanks! 谢谢!

You either need to call an AJAX method and pass in the necessary data for it to be able to complete the response that you want. 您要么需要调用一个AJAX方法,然后传递必要的数据,然后它才能完成所需的响应。 You can do either a GET or a POST. 您可以执行GET或POST。 On a GET put key value pairs on the query string, for a post put key value pairs in the POST body. 在查询字符串上的GET放置键值对上,对于POST正文中的后期放置键值对。 You can see jQuery AJAX docs for this. 您可以为此查看jQuery AJAX文档。 Looks like you will have to either do AJAX or a postback for your code to work as it requires user input. 看起来您将不得不执行AJAX或回发代码才能正常工作,因为它需要用户输入。

I'd suggest something like... 我建议像...

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

Thanks Sam for your input and sorry it wasn t clear what I needed to do. 感谢Sam的意见,对不起我不清楚我需要做什么。

I actually wanted to choose a partial view depending on which report the user selected from a dropdown list. 我实际上想根据用户从下拉列表中选择的报告来选择局部视图。

So in the view I used a .change so that we knew when the report had been chosen: 因此,在视图中,我使用.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>

In the controller I put a case statement so I knew which report I was on: 在控制器中,我写了一个案例声明,所以我知道我在写哪个报告:

//Here we are decinding which partial is going to be seen for which report (so which ajax call will be fired... //在这里我们确定将为哪个报告查看哪个部分(因此将触发哪个ajax调用...

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

and in the view I put an if statement using this to decide which report partial would be shown: 在视图中,我放置了一个if语句来确定将显示哪个报告部分:

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

I'm not sure if this is a really bad way of doing what i need but it seems to work. 我不确定这是否是我需要的真正糟糕的方法,但它似乎有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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