MVC: как я могу скрыть таблицу, если она не имеет значения - PullRequest
0 голосов
/ 01 февраля 2012

Привет, я новичок в mvc, и я пишу отчет, который получает данные по стране и розничному продавцу - если в стране нет розничного продавца, пустая таблица отображается с 0 с в столбцах.

Что яхотите, чтобы это сделать, это перейти к следующей стране и вообще не показывать таблицу для этой страны

Я использовал

ViewData["retailersForCountry"] = retailersForCountry;
if (retailersForCountry == 0)
{
    continue;
}

, но верхний и нижний колонтитулы таблицы по-прежнему отображаются -как я могу скрыть это полностью и просто показать следующую таблицу со значениями?

код контроллера:

case "CUMLEADS":
    // Report Title
    ViewData["title"] = reportRequest.Title;

    // Store the ReportRequest Id
    ViewData["reportRequestId"] = reportRequest.Id;

    // number Of COuntries so that we can set our outermost loop
    var numberOfCountriesCumLeads = Convert.ToInt32(_reportValueRepository.GetReportPair(reportRequest.Id, "numberOfCountries").Value);
    ViewData["numberOfCountries"] = numberOfCountriesCumLeads;

    // Our outermost country loop

    for (int cumLeadsI = 1; cumLeadsI <= numberOfCountriesCumLeads; cumLeadsI++)
    {
        int cumulativeTotalForCountry = 0;

        // Get the number of Retailers for this country -check that the amount of retailers is not 0 if it is then skip to next country
        var retailersForCountry = Convert.ToInt32(_reportValueRepository.GetReportPair(reportRequest.Id, "retailersForCountry" + cumLeadsI).Value);
        //TODO
        //If retailerForCountry = 0 then go to next country - need to remove the header footer
        ViewData["retailersForCountry"] = retailersForCountry;
        if (retailersForCountry == 0)
        {
            continue;
        }
        ViewData["retailersForCountry" + cumLeadsI] = retailersForCountry;

        var totalRetailPerCountry = new int[retailersForCountry + 1];

        for (int numRetailer = 1; numRetailer <= retailersForCountry; numRetailer++)
        {
            ViewData["retailer" + numRetailer + "forCountry" + cumLeadsI + "Name"] = _reportValueRepository.GetReportPair(reportRequest.Id, "retailer" + numRetailer + "forCountry" + cumLeadsI + "Name").Value;
        }

        // get the country name
        ViewData["country" + cumLeadsI + "Name"] = _reportValueRepository.GetReportPair(reportRequest.Id, "country" + cumLeadsI + "Name").Value;

        // We need to go through the dates in order

        // Create a loop that will go through the range of dates that we have in the request
        var myStartDate = reportRequest.StartDate;

        // I need to store in the view the total number of weeks that we are going to do, and then for each ith week store the week number and the date range for that week
        var actualEndDate = reportRequest.EndDate;
        TimeSpan timespan = actualEndDate.Subtract(myStartDate);
        int numberOfWeeks = timespan.Days / 7;
        ViewData["numberOfWeeks" + cumLeadsI] = numberOfWeeks;
        int cumLeadsJ = 1;

        while (myStartDate.CompareTo(reportRequest.EndDate) < 0)
        {
            int totalForWeek = 0;
            var myEndDate = myStartDate.AddDays(6);
            if (myEndDate.CompareTo(reportRequest.EndDate) > 0)
            {
                myEndDate = reportRequest.EndDate;
            }

            // Store the Range of the data for display
            ViewData["weekRange" + cumLeadsI + "Range" + cumLeadsJ] = myStartDate.ToShortDateString() + "-" + myEndDate.ToShortDateString();

            // Go through each of the retailers for this date and this country to do 1 row
            DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
            Calendar cal = dfi.Calendar;
            ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ] = cal.GetWeekOfYear(myStartDate, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);

            // I need to loop thougth each of the retailers for this country and get the values for this myStartDate to put into the view
            for (int cumLeadsK = 1; cumLeadsK <= retailersForCountry; cumLeadsK++)
            {
                var retailerForWeek = Convert.ToInt32(_reportValueRepository.GetReportPair(reportRequest.Id, "retailer" + cumLeadsK + "forCountry" + cumLeadsI + myStartDate + "Count").Value);
                ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ + "retailer" + cumLeadsK] = retailerForWeek;
                totalForWeek += retailerForWeek;
                totalRetailPerCountry[cumLeadsK] += retailerForWeek;
            }

            ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ + "totalForWeek"] = totalForWeek;
            cumulativeTotalForCountry += totalForWeek;
            ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ + "cumulativeForWeek"] = cumulativeTotalForCountry;

            // Move onto the next week
            myStartDate = myStartDate.AddDays(7);
            cumLeadsJ++;
        }

        int crossTotal = 0;
        // I need to loop though each of the retailers for this country and get the values for this myStartDate to put into the view
        for (int cumLeadsK = 1; cumLeadsK <= retailersForCountry; cumLeadsK++)
        {
            crossTotal += totalRetailPerCountry[cumLeadsK];
            ViewData["retailerTotalForCountry" + cumLeadsI + "RetailerTotal" + cumLeadsK] = totalRetailPerCountry[cumLeadsK];

        }
        ViewData["crossTotal" + cumLeadsI] = crossTotal;

        for (int cumLeadsK = 1; cumLeadsK <= retailersForCountry; cumLeadsK++)
        {
            ViewData["percentageForRetailer" + cumLeadsI + "RetailerPercentage" + cumLeadsK] = Convert.ToDouble(totalRetailPerCountry[cumLeadsK]) / Convert.ToDouble(crossTotal) * 100.0;
        }

        ViewData["numberOfWeeks"] = cumLeadsJ;
    }
    return View(report.Code);

Просмотр:

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%: ViewData["title"] %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h1 title="<%: ViewData["title"] %>">
        <%: ViewData["title"]%>
    </h1>
    <% for (int cumLeadsI = 1; cumLeadsI <= Convert.ToInt32(ViewData["numberOfCountries"]); cumLeadsI++)
       { %>

    <h2 title="<%: ViewData["country" + cumLeadsI + "Name"] %>">
        <%: ViewData["country" + cumLeadsI + "Name"] %></h2>
    <table style="font-size: 80%; border-collapse: collapse; margin-left: 10px;">
        <thead>
            <tr style="background-color: #f3f3f3; font-weight: bold;">
                <td>
                    &nbsp; Week&nbsp;
                </td>
                <td>
                    &nbsp; Week number&nbsp;
                </td>
                <% for (int numRetailer = 1; numRetailer <= Convert.ToInt32(ViewData["retailersForCountry" + cumLeadsI]); numRetailer++)
                   { %>
                <td>
                    &nbsp;
                    <%: ViewData["retailer" + numRetailer + "forCountry" + cumLeadsI + "Name"]%>&nbsp;
                </td>
                <% } %>
                <td>
                    &nbsp; Total&nbsp;
                </td>
                <td>
                    &nbsp; Cummulative Total&nbsp;
                </td>
            </tr>
        </thead>
        <tbody>
            <% for (int cumLeadsJ = 1; cumLeadsJ <= Convert.ToInt32(ViewData["numberOfWeeks"]); cumLeadsJ++)
               {%>
            <% if (cumLeadsJ % 2 != 0)
               { %>
            <tr>
                <% }
               else
               { %>
                <tr style="background-color: #f3f3f3;">
                    <% } %>
                    <td>
                        <%: ViewData["weekRange" + cumLeadsI + "Range" + cumLeadsJ] %>
                    </td>
                    <td>
                        <%: ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ] %>
                    </td>
                    <% for (int cumLeadsK = 1; cumLeadsK <= Convert.ToInt32(ViewData["retailersForCountry" + cumLeadsI]); cumLeadsK++)
                       { %>
                    <td>
                        <%: ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ + "retailer" + cumLeadsK] %>
                    </td>
                    <% } %>
                    <td>
                        <%: ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ + "totalForWeek"] %>
                    </td>
                    <td>
                        <%: ViewData["weekNumber" + cumLeadsI + "Range" + cumLeadsJ + "cumulativeForWeek"] %>
                    </td>
                </tr>
                <% } %>
        </tbody>
        <tfoot>
            <tr style="border-top: 1px solid black; font-weight: bold; background-color: #f3f3f3; ">
                <td style="text-align:left;">
                    Total
                </td>
                <td>
                    &nbsp;
                </td>
                <% for (int cumLeadsK = 1; cumLeadsK <= Convert.ToInt32(ViewData["retailersForCountry" + cumLeadsI]); cumLeadsK++)
                   {%>
                <td>
                    <%: ViewData["retailerTotalForCountry" + cumLeadsI + "RetailerTotal" + cumLeadsK] %>
                </td>
                <%
                   }%>
                <td>
                    &nbsp;
                </td>
                <td>
                    <%: ViewData["crossTotal" + cumLeadsI]%>
                </td>
            </tr>
            <tr style="font-weight: bold; background-color: #f3f3f3; border-bottom: 1px solid black; ">
                <td style="text-align:left;">
                    Reseller Share
                </td>
                <td>
                    &nbsp;
                </td>
                <% for (int cumLeadsK = 1; cumLeadsK <= Convert.ToInt32(ViewData["retailersForCountry" + cumLeadsI]); cumLeadsK++)
                   {%>
                <td>
                    &nbsp;
                    <%: Convert.ToDouble(ViewData["percentageForRetailer" + cumLeadsI + "RetailerPercentage" + cumLeadsK]).ToString("F")  %>%&nbsp;
                </td>
                <%
                   }%>
                <td>
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
        </tfoot>
    </table>

Спасибо

1 Ответ

1 голос
/ 01 февраля 2012

Краткий ответ: проверьте длину набора перед распечаткой таблицы. В вашем случае:

<% if(Convert.ToInt32(ViewData["retailersForCountry" + cumLeadsI]) > 0 ) {%>
  <table>
   .....

Длинный ответ, вы сами найдете такие вопросы, как этот, если вы очистите свой стиль. Например, вы должны никогда использовать класс Convert в представлении, и вам следует использовать структуру ViewData очень редко (это полезно для таких вещей, как «варианты заполнения раскрывающегося списка», но на самом деле не должно быть используется для многого другого). Вам просто нужно создать очень простой класс для нужных вам значений и использовать его через свойство Model (у вас должен быть тот же тип).

Кроме того, большинство людей перешли на использование шаблонов представления Razor, а не того, что вы используете (веб-формы). В некотором смысле это личное предпочтение, но оно достаточно похоже на то, что на изучение уйдет около 6 минут, и вы найдете почти все текущие примеры, написанные на Razor. Вот таблица быстрых эквивалентностей .

Я понимаю, что вышеупомянутое звучит довольно грубо, но вы можете свободно использовать StackOverflow в качестве ресурса - люди здесь помогут, и ваше кодирование действительно станет намного проще.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...