How do I maintain scroll position in MVC?

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

    10 years on and a different JS solution. The other JS solution waits for the page to scroll and when the page loads scrolls to whatever position was saved. That's fine for probably most folks (although it doesn't remove the value so the page would always scroll to that position when you reviewed that page...). My solution is to wait for the form to submit:

    (Yes, it is using jQuery, but the site has a lot of it...)

        // OWNER'S FORM POSITION
        if ($("[js-owner-request]").length) {
            $("[js-owner-request]").on("submit", function() {
                localStorage['owner-request__scrollTop'] = $(this).offset().top;
            });
    
            if (localStorage['owner-request__scrollTop'] !== "null") {
                $(document).scrollTop(localStorage['owner-request__scrollTop']);
                localStorage['owner-request__scrollTop'] = "null"; // set to null so we don't always scroll...
            }
        }
    

    This scrolls back to the top of the form, that way any error messages would be visible as you might have scrolled beyond the validation summary.

提交回复
热议问题