Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I maintain scroll position in MVC?

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 simple in the WebForms world is maintaining the scroll position on a page. All you do is set the MaintainScrollPositionOnPostback property to true. However, in MVC, Im not using postbacks so this will not work for me. What is the standard way of handling this?

Edit: Ajax is acceptable, but I was also wondering how you would do it without AJAX.

like image 879
Papa Burgundy Avatar asked Jan 27 '09 17:01

Papa Burgundy


People also ask

How do I scroll to a specific position in HTML?

The scrollTo() method scrolls the document to specified coordinates.


2 Answers

I've resolved this in JS :

$(document).scroll(function(){     localStorage['page'] = document.URL;     localStorage['scrollTop'] = $(document).scrollTop(); }); 

Then in document ready :

$(document).ready(function(){     if (localStorage['page'] == document.URL) {         $(document).scrollTop(localStorage['scrollTop']);     } }); 
like image 153
Madagaga Avatar answered Oct 04 '22 05:10

Madagaga


The way MaintainScrollPositionOnPostback works is that it has a pair of hidden fields: __SCROLLPOSITIONX and __SCROLLPOSITIONY

On a postback, it sets these,

function WebForm_GetScrollY() { if (__nonMSDOMBrowser) {     return window.pageYOffset; } else {     if (document.documentElement && document.documentElement.scrollTop) {         return document.documentElement.scrollTop;     }     else if (document.body) {         return document.body.scrollTop;     } } return 0; } function WebForm_SaveScrollPositionSubmit() {     if (__nonMSDOMBrowser) {         theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;         theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;     }     else {         theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();         theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();     }     if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {         return this.oldSubmit();     }     return true;     } 

and then it calls RestoreScrollPosition:

function WebForm_RestoreScrollPosition() {     if (__nonMSDOMBrowser) {         window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);     }     else {         window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);     }     if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {         return theForm.oldOnLoad();     }     return true; } 

But as most people said, MVC should be avoiding postbacks anyway.

like image 25
Richard Gadsden Avatar answered Oct 04 '22 06:10

Richard Gadsden