Невозможно изменить высоту div после добавления Layout - PullRequest
0 голосов
/ 23 октября 2018

У меня есть веб-страница просмотра бритвы, в которой есть div, в которую я каким-то образом заполняю данные (ленивая загрузка или цикл, не имеет значения).

Если я не использую макет, IE:

@{
    Layout = "_Layout";
}

Тогда div будет использовать мою настроенную высоту, а также при необходимости отобразит полосу прокрутки (используя overflow: auto)

Однако, когда я добавлю макет,даже пустая, я не могу изменить высоту div, из-за чего он поднимает весь экран с макета на нижнюю часть и не показывает прокрутки.

Что отключило мою возможность изменитьвысота?

(div im загружает данные в это div id container)

index.cshtml:

@{
    Layout = "_Layout";
}

<style>
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
        width: 100%;
    }

    th, td {
        padding: 5px;
        text-align: center;
        width: 15%;
    }

    .Good {
        background-color: green
    }

    .Bad {
        background-color: red
    }

    #container {
        background: #eee;
    }
</style>

<head>
    <script src="/JQuery/jquery-3.3.1.min.js"></script>
</head>

<body style="overflow: hidden;">

    <div>
        <div>
            <h3 id="Progression"></h3>
        </div>
        <div id="container" style="width: 100%; height: 80%; overflow: auto;">

        </div>
        <div id="progress" style="display: none; height: 20%">
            <h4>Loading...</h4>
        </div>
    </div>
</body>

_Layout.cshtml:

<!DOCTYPE html>
<style>
    .main-header {
        background: url(/images/bg-header.png) transparent repeat-x 0 0;
    }
</style>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
</head>
<body>
    <header class="main-header" role="banner">
        <div>
            <a href="/" title="Home" rel="home">
                <img src="/images/COMPANY-logo.png" style="background-color:white;" alt="Home">
            </a>

        </div>
    </header>
<div>
    @RenderBody()
</div>
</body>
</html>

Пусто _Layout.cshtml: (спроблемы с этим макетом)

<!DOCTYPE html>
<style>
    .main-header {
        background: url(/images/bg-header.png) transparent repeat-x 0 0;
    }
</style>
<html>
<head>
</head>
<body>

<div>
    @RenderBody()
</div>
</body>
</html>

Созданная страница (использовался пустой макет):

<!DOCTYPE html>
<style>
    .main-header {
        background: url(/images/bg-header.png) transparent repeat-x 0 0;
    }
</style>
<html>
<head>
</head>
<body>

<div>

<style>
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
        width: 100%;
    }

    th, td {
        padding: 5px;
        text-align: center;
        width: 15%;
    }

    .Good {
        background-color: green
    }

    .Bad {
        background-color: red
    }

    #container {
        background: #eee;
    }
</style>

<head>
    <script src="/JQuery/jquery-3.3.1.min.js"></script>
</head>

<body style="overflow: hidden;">

    <div>
        <div>
            <h3 id="Progression"></h3>
        </div>
        <div id="container" style="width: 100%; height: 80%; overflow: auto;">

        </div>
        <div id="progress" style="display: none; height: 20%">
            <h4>Loading...</h4>
        </div>
    </div>
</body>

<script>
    var pageSize = 50;
    var pageIndex = 0;
    var totalItemsDisplayed = 0;

    $(document).ready(function() {
        lazyLoadCards(0);
        $('#container').scroll(function() {
            var scrollTop = $(this).scrollTop();
            var scrollHeight = $(this).prop('scrollHeight');
            var clientHeight = $(this).prop('clientHeight');

            if (scrollTop + clientHeight === scrollHeight) {
                pageIndex++;
                lazyLoadCards(pageIndex);
            }
        });

        function lazyLoadCards(index) {
            $.ajax({
                type: 'GET',
                url: '/AllCards/OnScrollEnd',
                data: { "startIndex": index, "size": pageSize },
                dataType: 'json',
                success: function(data) {
                    if (data != null) {
                        totalItemsDisplayed += data.length;
                        for (var i = 0; i < data.length; i++) {
                            $("#container").append("<h2>" +
                                data[i].cardNumber +
                                "</h2>");
                        }

                        updateProgression();
                    }
                },
                beforeSend: function() {
                    $("#progress").show();
                },
                complete: function() {
                    $("#progress").hide();
                },
                error: function() {
                    alert("Error while retrieving data!");
                }
            });
        }

        function loadCards(index) {
            $.ajax({
                type: 'GET',
                url: '/AllCards/OnScrollEnd',
                data: { "startIndex": index, "size": pageSize },
                dataType: 'json',
                success: function(data) {
                    if (data != null) {
                        totalItemsDisplayed += data.length;
                        for (var i = 0; i < data.length; i++) {
                            $("#container").append("<h2>" +
                                data[i].cardNumber +
                                "</h2>");
                        }
                        updateProgression();
                        if (data.length > 0) {
                            loadCards(index + 1);
                        }
                    }
                },
                beforeSend: function() {
                    $("#progress").show();
                },
                complete: function() {
                    $("#progress").hide();
                },
                error: function() {
                    alert("Error while retrieving data!");
                }
            });
        }

        function updateProgression() {
            $('#Progression').text("Displaying " +  totalItemsDisplayed + " Cards out of " +  6930);
        }
    });

</script>
</div>
</body>
</html>

Визуальное отображение текущего результата и желаемого результата: (Обратите внимание, что текст внутри серого поля - это просто элементы с некоторым текстом.вот что делает вызов ajax) Visual to see current output

Сгенерированный код после добавления @section и @style и удаления тела всех, кроме _Layout

<!DOCTYPE html>
<html>
<head>
    <style>
        .main-header {
            background: url(/images/bg-header.png) transparent repeat-x 0 0;
        }
    </style>

    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            width: 100%;
        }

        th, td {
            padding: 5px;
            text-align: center;
            width: 15%;
        }

        .Good {
            background-color: green
        }

        .Bad {
            background-color: red
        }

        #container {
            background: #eee;
        }
    </style>

</head>
<body>
<header class="main-header" role="banner">
    <div>
        <a href="/" title="Home" rel="home">
            <img src="/images/COMPANY-logo.png" style="background-color:white;" alt="Home">
        </a>
    </div>
</header>
<div>

<div>
    <div>
        <h3 id="Progression"></h3>
    </div>
    <div id="container" style="width: 100%; height: 80%; overflow: visible;">

    </div>
    <div id="progress" style="display: none; height: 20%">
        <h4>Loading...</h4>
    </div>
</div>




</div>

    <script src="/JQuery/jquery-3.3.1.min.js"></script>
    <script>
    var pageSize = 50;
    var pageIndex = 0;
    var totalItemsDisplayed = 0;

    $(document).ready(function() {
        lazyLoadCards(0);
        $('#container').scroll(function() {
            var scrollTop = $(this).scrollTop();
            var scrollHeight = $(this).prop('scrollHeight');
            var clientHeight = $(this).prop('clientHeight');

            if (scrollTop + clientHeight === scrollHeight) {
                pageIndex++;
                lazyLoadCards(pageIndex);
            }
        });

        function lazyLoadCards(index) {
            $.ajax({
                type: 'GET',
                url: '/AllCards/OnScrollEnd',
                data: { "startIndex": index, "size": pageSize },
                dataType: 'json',
                success: function(data) {
                    if (data != null) {
                        totalItemsDisplayed += data.length;
                        for (var i = 0; i < data.length; i++) {
                            $("#container").append("<h2>" +
                                data[i].cardNumber +
                                "</h2>");
                        }

                        updateProgression();
                    }
                },
                beforeSend: function() {
                    $("#progress").show();
                },
                complete: function() {
                    $("#progress").hide();
                },
                error: function() {
                    alert("Error while retrieving data!");
                }
            });
        }

        function loadCards(index) {
            $.ajax({
                type: 'GET',
                url: '/AllCards/OnScrollEnd',
                data: { "startIndex": index, "size": pageSize },
                dataType: 'json',
                success: function(data) {
                    if (data != null) {
                        totalItemsDisplayed += data.length;
                        for (var i = 0; i < data.length; i++) {
                            $("#container").append("<h2>" +
                                data[i].cardNumber +
                                "</h2>");
                        }
                        updateProgression();
                        if (data.length > 0) {
                            loadCards(index + 1);
                        }
                    }
                },
                beforeSend: function() {
                    $("#progress").show();
                },
                complete: function() {
                    $("#progress").hide();
                },
                error: function() {
                    alert("Error while retrieving data!");
                }
            });
        }

        function updateProgression() {
            $('#Progression').text("Displaying " +  totalItemsDisplayed + " Cards out of " +  6930);
        }
    });

    </script>

</body>
</html>

1 Ответ

0 голосов
/ 23 октября 2018

Вы должны использовать разделы .Разделы позволяют добавлять стили, сценарии и т. Д. В макет.У вас не может быть тегов head и body, кроме страницы макета.

Пусто _Layout.cshtml:

<!DOCTYPE html>
<head>
    <style>
        .main-header {
            background: url(/images/bg-header.png) transparent repeat-x 0 0;
        }
    </style>
    @RenderSection("Styles", required: false)
</head>
    <body>
        <div>
            @RenderBody()
        </div>
        @RenderSection("Scripts", required: false)
    </body>
</html>

Index.cshtml:

@{
    Layout = "_Layout";
}
@section Styles {
<style>
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
        width: 100%;
    }

    th, td {
        padding: 5px;
        text-align: center;
        width: 15%;
    }

    .Good {
        background-color: green
    }

    .Bad {
        background-color: red
    }

    #container {
        background: #eee;
    }
</style>
}

<div>
    <div>
        <h3 id="Progression"></h3>
    </div>
    <div id="container" style="width: 100%; height: 80%; overflow: auto;">

    </div>
    <div id="progress" style="display: none; height: 20%">
        <h4>Loading...</h4>
    </div>
</div>  
@section Scripts {
        <script src="/JQuery/jquery-3.3.1.min.js"></script>
}

ОБНОВЛЕНИЕ

Необходимо внести следующие изменения:

<div id="container" style="width: 100%;height: 155px;overflow: scroll;display: block;">

Нельзя использовать процент для высотыесли вы не добавите position:absolute;.Если вам нужна только вертикальная полоса прокрутки, вам нужно использовать overflow-y:scroll;.

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