How do I maintain scroll position in MVC?

后端 未结 12 1923
情歌与酒
情歌与酒 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:34

    Taking inspiration from WebForms and the answer provided by Richard Gadsden, another approach using javascript and the form collection could look something like this:

    @{
        var scrollPositionX = string.Empty;        
        if(IsPost) {
            scrollPositionX = Request.Form["ScrollPositionX"];
        }
    }
    
    
    $("#Submit").click(function () { $("#ScrollPositionX").val($(document).scrollTop()); }); $("#ScrollPositionX").each(function () { var val = parseInt($(this).val(), 10); if (!isNaN(val)) $(document).scrollTop(val); });

    The code provided is for inspiration and is in no way prettified. It could probably be done in a few different ways, I guess it all comes down to how you decide to persist the scrollTop value of your document across the POST. It is fully working and should be cross browser safe since we are using jQuery to do the scrolling. I believe the code provided is self-explanatory, but I will be happy to provide a more detailed description on whats going on, just let me know.

提交回复
热议问题