How do I maintain scroll position in MVC?

后端 未结 12 1928
情歌与酒
情歌与酒 2020-11-27 18:02

Im working on a project in MVC and have enjoyed learning about it. There are a few growing pains but once you figure them out it\'s not bad. One thing that is really simpl

12条回答
  •  迷失自我
    2020-11-27 18:22

    I use .scrollTop like shown below, very easy, it even works with multiple forms in the view (I have a very long view, broken down into multiple forms):

    First put this property inside the model:

                   public string scrollTop { get; set; }
    

    And in the view, inside Form #1:

                   @Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm1"})
    

    inside Form #2:

                   @Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm2"})
    

    inside Form #2:

                   @Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm3"})
    

    and then at the bottom of the view:

     $(document).ready(function () {
        $(document).scrollTop(@Model.scrollTop);
        $(document).scroll(function () {
            $("#ScrollForm1").val($(document).scrollTop());
            $("#ScrollForm2").val($(document).scrollTop());
            $("#ScrollForm3").val($(document).scrollTop());
          });
       });
    

    Your scroll position is always preserved upon postback because the @Html.HiddenFor fields store your current scroll and pass it to the model on post. And then, when the page comes up it gets the scrollTop value from the model. At the end your page would behave like webform, everything stays intact.

提交回复
热议问题