Link to home
Start Free TrialLog in
Avatar of kvishnusharma
kvishnusharmaFlag for Afghanistan

asked on

ASP.NET MVC scroll position maintain

Hi,

I recently took upon solving a long standing persisting problem in our project. One of our developer used jquery to maintain the scroll position in the asp.net mvc application. It is from the below link.

http://stackoverflow.com/questions/7278295/asp-net-mvc3-razor-maintain-scroll-position-on-postback

$(function(){
  var posName = location.href + "_top";
  $(window).unload(function() {
    var top = $(document).scrollTop();
    $.cookie(posName, top);
  });

  var goTop = parseInt($.cookie(posName));
  if (goTop) {
    $(document).scrollTop(goTop);
    $.cookie(posName, "");
  }
});

It was working fine until we used razor engine in the UI. However, due to some unfathomable reasons, this particular ASP.NET MVC UI has been moved to ASPX engine.
Now the problem started showing up. It jumps to the top of the page at the first postback after the page load. For the subsequent postbacks, it generally maintains the scroll position.

Is there a elegant way to maintain the scroll position?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kvishnusharma

ASKER

Hi,

Thanks for your quick response. I have replaced my current code by your code snippet, like below.

if (window.jQuery) {
         $(function () {
             var top = parseInt($.cookie("top"));
             if (top) $(document).scrollTop(top);
             $(document).scroll(function() {
                 var top = $(document).scrollTop();
                 $.cookie("top", top);
             });
         });
     }    

However, it is still jumping to the top on the first click/postback.

Any clues?

Thanks
Vishnu
did you included the right jquery cookies plugin?
I am using "jquery.cookie.js"..I am not sure which version is it though.

I found this in the header of that file..

/*jshint eqnull:true */
/*!
 * jQuery Cookie Plugin v1.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */

Am I using the correct version?
it's ok, I know plugin, it's not really the version i'm looking for.

Do you've a link to see the site?
This site is not live yet. I have attached two files, Site.Master and Index.aspx. This should give you an idea of the set up.

Thanks
Site.Master
Index.aspx
Add an alert to be sure we get the value after a postback and confirm you get different value at page load depending where you leave the scrollbar

if (window.jQuery) {
         $(function () {
             var top = parseInt($.cookie("top"));
             if (top) { 
                alert("top: "+top);
                $(document).scrollTop(top);
             }
             $(document).scroll(function() {
                 var top = $(document).scrollTop();
                 $.cookie("top", top);
             });
         });
     }     

Open in new window

Here are the observations,

1. First click/postback: it's not showing the alert.

2. Subsequent clicks/postbacks: It's showing alerts with position number.

3. If the scroll position is in '0', it is not showing any alerts. Alerts are only displayed from '1'.

Am I missing something here?
when you get a good number for example 80
and do postback you confirm you get 80 and it don't scroll?
First click/postback doesn't show any alert. However, subsequent clicks/postbacks are showing position number and it doesn't scroll. It maintains the scroll position.

In short, as soon as the page loads, if we scroll down and do the first click/postback, it scrolls back to the top of the page. It doesn't maintain the scroll position on the first click/postback.
It will not maintain it but it will put back its position before the post back

Could you confirm you don't see any hashtag in the URL?

Replace : $(function () {
By : $(window).load(function() {
I have changed the jquery changed as below, however, it is still jumping to the top of the page on first click and I don't have any hashtag in the URL.


 if (window.jQuery) {
             $(window).load(function () {
             var top = parseInt($.cookie("top"));
                 if (top) {
                    alert("top: "+top);
                     $(document).scrollTop(top);
                 }
                 $(document).scroll(function() {
                     var top = $(document).scrollTop();
                     $.cookie("top", top);
                 });
             });
        }
Do you observe a scroll on the first click BEFORE the reloading of the page?
As soon as I run the project, (visual studio 2010), a vertical scroll is visible on the web page. I am not sure, if I had answered your question correctly.

and also web page appears with the scroll at the top of the page.
ok, so you get the scroll value BUT it go to the top...

for testing purpose, we're goint o use a timer to see what happen if we run the code after some init at page load, we trry TEN SECONDS FIRST, scroll down, click to do a postback, and don't touch anything during this ten seconds :

 if (window.jQuery) {
             $(window).load(function () {
setTimeout(function() {
             var top = parseInt($.cookie("top"));
                 if (top) {
                     $(document).scrollTop(top);
                    alert("top: "+top);
                 }
}, 10000);
                 $(document).scroll(function() {
                     var top = $(document).scrollTop();
                     $.cookie("top", top);
                 });
             });
        }

Open in new window

ok, so you get the scroll value BUT it go to the top...

No...for the first click/postback, I don't get the scroll value or alerts and I just go to the top.

for the subsequent clicks/postbacks, I get the alerts and maintain the scroll position.

I tried your ten second testing. For the first click/postback, I don't get any alert or scroll value, even after waiting for atleast 30 seconds.

But for subsequent clicks, I go to top, but after ten seconds, it is showing the alert and moving the page back to scroll position.
please confirm you change the scrollbar position before each click especially the first one
	if(window.jQuery) {
		$(window).load(function () {
			alert( "current: " + parseInt($.cookie("top")) );
			setTimeout(function() {
				var top = parseInt($.cookie("top"));
				if(top) {
					$(document).scrollTop(top);
					alert("top: "+top);
				}
			}, 10000);
			$(document).scroll(function() {
				var top = $(document).scrollTop();
				$.cookie("top", top);
			});
		});
	}

Open in new window

Before the first click what is the url ? Could you confirm we don't have a different domain AND protocol? Cookies are based on this as you know
please confirm you get an alert with "current"
why are you testing for jQuery line 1?
that mean without jQuery we can change scroll position
I used your jquery and these are the observations.

Whenever, I run my application on the visual studio, it takes me to the welcome page. I make my selections and it redirects to the actual page.

As soon as it redirects to the actual page, it is showing an alert i.e. "Current NaN".

and I scroll a little bit, and do the first click, and it shows the alert, "Current NaN", and goes to the top of the page.

Now, I do the second click, and it displays "Current 294", goes to the top. After ten seconds, alerts "top: 294" and moves to the corresponding scroll position.

Since, I am running this web site from visual studio 2010, I don't think the pages are from different domains or protocols.

and I didn't quite understand the following,

why are you testing for jQuery line 1?
that mean without jQuery we can change scroll position
why this line : if(window.jQuery) { ?

it takes me to the welcome page
As soon as it redirects to the actual page, it is showing an alert i.e. "Current NaN".

normal because you did not scroll so no saving of the scrollbar position

try this and confirm the alert you got :
	if(window.jQuery) {
		$(window).load(function () {
			setTimeout(function() {
				var top = parseInt($.cookie("top"));
				if(top) {
					$(document).scrollTop(top);
					alert("top: "+top);
				}
			}, 10000);
			$(document).scroll(function() {
				var top = $(document).scrollTop();
				$.cookie("top", top);
			});
		});
		$(window).bind("beforeunload", function () {
			var top = $(document).scrollTop();
			alert("saving position top: "+top);
			$.cookie("top", top);
		})
	}
	else {
		alert("no jQuery");
	}

Open in new window

Following are my observations,

I opened the web page through the welcome screen,

1) I scrolled a little bit, and did my first click. It showed two alerts, i.e. saving position top: e.g. 570. and page went back to top.

2) I waited for more than 10 seconds (nothing happened).

3) I did my second click, two alerts showed up, i.e. saving position top: e.g. 480. and page went back to top.

4) waited for 10 seconds, it showed another alert, "top: 480". and scroll position is maintained.

other observations, on closing or refreshing the browser, "saving position top: ##" alert is showing up.

However, for the first click, we are getting "saving position top" alert, but NOT "top:##" alert.
could you add a asp:textbox in your page :
<asp:TextBox ID="hidden" runat="server" Text="0" />

and put this :
$("#<%= hidden.ClientID %>").val(top);
after or before :
$.cookie("top", top);

so each time you scroll you should see the value of the scrollbar position
before clicking too
after postback too

if the value is good we will use it instead the cookie
This is promising...I have included asp:Textbox inside a form and made changes to the jquery. I observed that it is displaying the scroll position as soon as I scroll.

Now, how should I use this to maintain my scroll position?
So you confirm you see the right value inside after the first click (which not currenty work) ?
On page loading (during start up), when I scroll, the values in the textbox changes to show the scroll value. However, when I do the first click, the scroll goes to top of the page and also the value inside the textbox changes to zero.

after first click, the scroll is maintained and text box shows the scroll value.
OK, so there a process whic scroll to the top,  

<<when I do the first click>>
It's a link or a button? Could you post the html for the button?

Will be difficult to help you if I don't see the page for now, hope you're understand
Hi,

I have attached three files that are important to generate the necessary html code. There is the C# helper class called Extension.cs, which is used by the index.aspx file, to generate the html code from the view model class. Please let me know if you need additional information to resolve this issue.

Thanks
Extensions.cs
Site.Master
Index.aspx
could you setup a test page somewhere?
Hi,

I couldn't get back to you sooner, I was doing some internal testing on this issue. I have created a sample app to recreate the same error (Jumping to the top on first select/click/postback). We deployed this particular app/website on our development server (windows server 2003), it was showing the same error. However, when I deployed the same website on the windows azure (see link below), it was not showing the error.

I believe, it has something to do with .NET version (3.5), MVC (2.0), and server (2003). In any case, please look at this site and let me know your thoughts on the entire issue.

http://sixperhouse.azurewebsites.net/

In the above link, scroll a little bit and you can see a drop down. When you select something and goes to the top, then it has error, otherwise, it is working fine.

Last time I checked, scroll is properly maintained.

- Vishnu
The only erro I got was on IE10 :

HTML1524: DOCTYPE non valide. La déclaration valide la plus courte est « <!DOCTYPE html> ».

So try to use this simple DOCTYPE :
<!DOCTYPE html>

Open in new window