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?
我正在用MVC做一个项目,我很喜欢学习它。有一些成长的烦恼,但一旦你发现它们并不是坏事。WebForms中最简单的一件事就是保持页面上的滚动位置。您所做的就是将MaintainScrollPositionOnPostback属性设置为true。但是,在MVC中,我不使用回发,所以这对我来说行不通。处理这个问题的标准方法是什么?
Edit: Ajax is acceptable, but I was also wondering how you would do it without AJAX.
编辑:Ajax是可以接受的,但是我也想知道如果没有Ajax,你会怎么做。
11 个解决方案
#1
8
The way MaintainScrollPositionOnPostback works is that it has a pair of hidden fields: __SCROLLPOSITIONX and __SCROLLPOSITIONY
在postback工作的过程中,它有两个隐藏的字段:__SCROLLPOSITIONX和__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:
然后它调用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.
但是正如大多数人所说,MVC应该避免回发。
#2
28
I've resolved this in JS :
我用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']);
}
});
#3
6
Actually there is no standard way of handling this, this was a Microsoft hack to support their post back model. They needed this because every control did a post back and the user would constantly be pushed back to the top of the page.
实际上没有标准的方法来处理这个问题,这是微软为支持他们的后端模式而设计的一个黑客。他们需要这样做,因为每个控件都回发一个帖子,用户会被不断地推到页面的顶部。
The recommendation for use with MVC is to do most of your post back to servers using AJAX. So that the page doesn't have to rerender the the focus is not moved. jQuery makes AJAX really easy, and there is even default forms like
使用MVC的建议是使用AJAX返回服务器。这样页面就不需要重新运行焦点了。jQuery使AJAX变得非常简单,甚至还有像这样的默认表单
<% Ajax.BeginForm(...) %>
Which will take care of the AJAX side of things for you.
这将为您解决AJAX方面的问题。
#4
4
Taking inspiration from WebForms and the answer provided by Richard Gadsden, another approach using javascript and the form collection could look something like this:
从WebForms和Richard Gadsden提供的答案中获得灵感,另一种使用javascript和表单集合的方法可以如下所示:
@{
var scrollPositionX = string.Empty;
if(IsPost) {
scrollPositionX = Request.Form["ScrollPositionX"];
}
}
<form action="" method="post">
<input type="hidden" id="ScrollPositionX" name="ScrollPositionX" value="@scrollPositionX" />
<input type="submit" id="Submit" name="Submit" value="Go" />
</form>
$("#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.
所提供的代码是为了激发灵感,而不是为了美化。它可以通过几种不同的方式来实现,我想这都取决于您如何决定在整个POST中持久化您的文档的scrollTop值。它完全可以工作,并且应该是跨浏览器安全的,因为我们正在使用jQuery进行滚动。我相信所提供的代码是不言自明的,但是我很乐意提供关于正在发生的事情的更详细的描述,请让我知道。
#5
3
My own workaround is using some info in the ViewData
to know what area must be shown in the backnavigation, and a little javascript to position the page's cursor:
我自己的解决方案是使用ViewData中的一些信息来了解在backnavigation接口中必须显示的区域,并使用一些javascript来定位页面的光标:
In the View, an element like this:
在视图中,这样的元素:
<h3 id="tasks">
Contained tasks
</h3>
And the javascript to repositionate the page:
以及重新定位页面的javascript:
<script type="text/javascript">
addOnLoad(goAnchor);
function goAnchor() {
var paging = <%= //Here you determine (from the ViewData or whatever) if you have to position the element %>;
if (paging == "True") {
window.location.hash = "tasks";
}
</script>
You could use a switch
to determine what element from the view page you must relocate.
您可以使用一个开关来确定必须重新定位视图页面中的哪些元素。
Hope it helps.
希望它可以帮助。
#6
2
<%
if(!ViewData.ModelState.IsValid)
{
%>
window.location.hash = 'Error';
<%
}
%>
<a name="Error"></a>
#7
1
I used name attributes in tags. No javascript used.
我在标签中使用了名称属性。不使用javascript。
The page that I wanted to return to had <a> tags with name attribute, e.g. <a name="testname">.
我想要返回的页面具有标记和name属性,例如。
The page (view) I returned from used tag <a href="<%: Request.UrlReferrer %>#testname">Back</a>". Request.UrlReferrer is used to go to previous page. #testname scrolls the page position to tag with name "testname".
我从使用的标记 # testname " > < / >”。请求。UrlReferrer用于访问前一页。#testname滚动页面位置以标记“testname”。
#8
1
Here's a simple, pure Javascript solution which I've tested in FF4 and IE9 only.
这里有一个简单的纯Javascript解决方案,我只在FF4和IE9中测试过。
The idea is that this solution should degrade gracefully by falling back to the standard #anchor
tags on a page. What I'm doing is replacing those #anchor
tags on the fly with the X and Y coordinates, then on load, I simply read those values from the querystring and scroll there. If this fails for some reason, the browser should still navigate to the #anchor
position...
其思想是,这个解决方案应该通过回到页面上的标准#anchor标签来优雅地降级。我所做的就是用X和Y坐标替换那些#anchor标签,然后在load时,我只需从querystring中读取这些值并在那里滚动。如果由于某种原因失败,浏览器仍然应该导航到#anchor的位置……
Markup:
标记:
<a href="/somecontroller/someaction/#someanchor">My Link</a>
jQuery:
jQuery:
$(function() {
// RESTORE SCROLL POSITION
RestoreScrollPosition();
// SAVE SCROLL POSITION
$('a:not(a[href^="http"])').filter('[href$="#someanchor"]').each(function() {
$(this).click(function() {
var href = $(this).attr('href').replace("#someanchor","");
if (href.indexOf('?') == -1) {
href = href + '?x='
} else {
href = href + '&x='
}
href = href + window.pageXOffset;
href = href + '&y=' + window.pageYOffset;
$(this).attr('href', href);
});
});
}
A couple of helper methods:
一些辅助方法:
function RestoreScrollPosition() {
var scrollX = gup('x');
var scrollY = gup('y');
if (scrollX != null && scrollY != null) {
window.scrollTo(scrollX, scrollY);
return true;
}
return false;
}
function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
This fits my needs, but could be more generic/reusable - I'd be happy for someone to improve on this... :-)
这符合我的需求,但可以更通用/可重用——我很高兴有人能在这方面做出改进……:-)
#9
0
a very not-nice way to do this is using cookies.
一种不太好的方法是使用cookie。
If you use ONE page in your MVC which handles the other pages you could a code-snippet to it that loads every page which creates a cookie (if non-existent) called "scrolltop". There are ways to have javascript automatically update this cookie when the user scrolls up or down by catching these events or watching the scrollTop value.
如果您在MVC中使用一个页面来处理其他页面,那么您可以使用一个代码段来加载每个页面,这些页面会创建一个名为“scrolltop”的cookie(如果不存在的话)。通过捕获这些事件或查看scrollTop值,可以让javascript在用户向上或向下滚动时自动更新此cookie。
On a new page you just have to load the saved position and make the view scroll there in 0 milliseconds (with Mootools or any Ajax script this should be possible) and the user will be exactly where they were.
在一个新页面上,您只需加载保存的位置,并使视图在0毫秒内滚动到那里(使用Mootools或任何Ajax脚本都可以),用户就会在它们所在的位置。
I don't know much about asp so I don't know if a method exists to anchor to a current y-position. Javascript is a fast and easy way. Anchors in HTMl could be an option if you had every element anchored and posted the anchor to other pages.
我不太了解asp,所以我不知道是否存在一个方法来固定到当前的y位置。Javascript是一种快速简单的方法。如果每个元素都被锚定并将锚点发布到其他页面,那么可以使用HTMl中的锚点。
#10
0
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):
我使用如下所示的.scrollTop,非常简单,它甚至可以处理视图中的多种形式(我有一个很长的视图,可以分解成多种形式):
First put this property inside the model:
首先将该属性放入模型中:
public string scrollTop { get; set; }
And in the view, inside Form #1:
在视图内,表单#1:
@Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm1"})
inside Form #2:
内部形式# 2:
@Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm2"})
inside Form #2:
内部形式# 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.
您的滚动位置总是在回发后保留,因为@Html。HiddenFor字段存储当前滚动并将其传递给post上的模型。然后,当页面出现时,它从模型中获取scrollTop值。最后你的页面会表现得像webform,一切都保持原样。
#11
-1
@{
}
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var div = document.getElementById("dvScroll");
var div_position = document.getElementById("div_position");
var position = parseInt(@Request.Form("div_position"));
if (isNaN(position)) {
position = 0;
}
div.scrollTop = position;
div.onscroll = function () {
div_position.value = div.scrollTop;
};
};
</script>
</head>
<body>
<div id="dvScroll" style="overflow-y: scroll; height: 260px; width: 300px">
1. This is a sample text
<br />
2. This is a sample text
<br />
3. This is a sample text
<br />
4. This is a sample text
<br />
5. This is a sample text
<br />
6. This is a sample text
<br />
7. This is a sample text
<br />
8. This is a sample text
<br />
9. This is a sample text
<br />
10. This is a sample text
<br />
11. This is a sample text
<br />
12. This is a sample text
<br />
13. This is a sample text
<br />
14. This is a sample text
<br />
15. This is a sample text
<br />
16. This is a sample text
<br />
17. This is a sample text
<br />
18. This is a sample text
<br />
19. This is a sample text
<br />
20. This is a sample text
<br />
21. This is a sample text
<br />
22. This is a sample text
<br />
23. This is a sample text
<br />
24. This is a sample text
<br />
25. This is a sample text
<br />
</div>
<hr />
<form method="post">
<input type="hidden" id="div_position" name="div_position" />
<input type="submit" value="Cool" />
</form>
</body>
</html>
You can use this to maintain scroll Position after postback.
在回发后,您可以使用它来保持滚动位置。
Source: http://www.aspsnippets.com/Articles/Maintain-Scroll-Position-of-DIV-on-PostBack-in-ASPNet.aspx
来源:http://www.aspsnippets.com/Articles/Maintain-Scroll-Position-of-DIV-on-PostBack-in-ASPNet.aspx
#1
8
The way MaintainScrollPositionOnPostback works is that it has a pair of hidden fields: __SCROLLPOSITIONX and __SCROLLPOSITIONY
在postback工作的过程中,它有两个隐藏的字段:__SCROLLPOSITIONX和__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:
然后它调用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.
但是正如大多数人所说,MVC应该避免回发。
#2
28
I've resolved this in JS :
我用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']);
}
});
#3
6
Actually there is no standard way of handling this, this was a Microsoft hack to support their post back model. They needed this because every control did a post back and the user would constantly be pushed back to the top of the page.
实际上没有标准的方法来处理这个问题,这是微软为支持他们的后端模式而设计的一个黑客。他们需要这样做,因为每个控件都回发一个帖子,用户会被不断地推到页面的顶部。
The recommendation for use with MVC is to do most of your post back to servers using AJAX. So that the page doesn't have to rerender the the focus is not moved. jQuery makes AJAX really easy, and there is even default forms like
使用MVC的建议是使用AJAX返回服务器。这样页面就不需要重新运行焦点了。jQuery使AJAX变得非常简单,甚至还有像这样的默认表单
<% Ajax.BeginForm(...) %>
Which will take care of the AJAX side of things for you.
这将为您解决AJAX方面的问题。
#4
4
Taking inspiration from WebForms and the answer provided by Richard Gadsden, another approach using javascript and the form collection could look something like this:
从WebForms和Richard Gadsden提供的答案中获得灵感,另一种使用javascript和表单集合的方法可以如下所示:
@{
var scrollPositionX = string.Empty;
if(IsPost) {
scrollPositionX = Request.Form["ScrollPositionX"];
}
}
<form action="" method="post">
<input type="hidden" id="ScrollPositionX" name="ScrollPositionX" value="@scrollPositionX" />
<input type="submit" id="Submit" name="Submit" value="Go" />
</form>
$("#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.
所提供的代码是为了激发灵感,而不是为了美化。它可以通过几种不同的方式来实现,我想这都取决于您如何决定在整个POST中持久化您的文档的scrollTop值。它完全可以工作,并且应该是跨浏览器安全的,因为我们正在使用jQuery进行滚动。我相信所提供的代码是不言自明的,但是我很乐意提供关于正在发生的事情的更详细的描述,请让我知道。
#5
3
My own workaround is using some info in the ViewData
to know what area must be shown in the backnavigation, and a little javascript to position the page's cursor:
我自己的解决方案是使用ViewData中的一些信息来了解在backnavigation接口中必须显示的区域,并使用一些javascript来定位页面的光标:
In the View, an element like this:
在视图中,这样的元素:
<h3 id="tasks">
Contained tasks
</h3>
And the javascript to repositionate the page:
以及重新定位页面的javascript:
<script type="text/javascript">
addOnLoad(goAnchor);
function goAnchor() {
var paging = <%= //Here you determine (from the ViewData or whatever) if you have to position the element %>;
if (paging == "True") {
window.location.hash = "tasks";
}
</script>
You could use a switch
to determine what element from the view page you must relocate.
您可以使用一个开关来确定必须重新定位视图页面中的哪些元素。
Hope it helps.
希望它可以帮助。
#6
2
<%
if(!ViewData.ModelState.IsValid)
{
%>
window.location.hash = 'Error';
<%
}
%>
<a name="Error"></a>
#7
1
I used name attributes in tags. No javascript used.
我在标签中使用了名称属性。不使用javascript。
The page that I wanted to return to had <a> tags with name attribute, e.g. <a name="testname">.
我想要返回的页面具有标记和name属性,例如。
The page (view) I returned from used tag <a href="<%: Request.UrlReferrer %>#testname">Back</a>". Request.UrlReferrer is used to go to previous page. #testname scrolls the page position to tag with name "testname".
我从使用的标记 # testname " > < / >”。请求。UrlReferrer用于访问前一页。#testname滚动页面位置以标记“testname”。
#8
1
Here's a simple, pure Javascript solution which I've tested in FF4 and IE9 only.
这里有一个简单的纯Javascript解决方案,我只在FF4和IE9中测试过。
The idea is that this solution should degrade gracefully by falling back to the standard #anchor
tags on a page. What I'm doing is replacing those #anchor
tags on the fly with the X and Y coordinates, then on load, I simply read those values from the querystring and scroll there. If this fails for some reason, the browser should still navigate to the #anchor
position...
其思想是,这个解决方案应该通过回到页面上的标准#anchor标签来优雅地降级。我所做的就是用X和Y坐标替换那些#anchor标签,然后在load时,我只需从querystring中读取这些值并在那里滚动。如果由于某种原因失败,浏览器仍然应该导航到#anchor的位置……
Markup:
标记:
<a href="/somecontroller/someaction/#someanchor">My Link</a>
jQuery:
jQuery:
$(function() {
// RESTORE SCROLL POSITION
RestoreScrollPosition();
// SAVE SCROLL POSITION
$('a:not(a[href^="http"])').filter('[href$="#someanchor"]').each(function() {
$(this).click(function() {
var href = $(this).attr('href').replace("#someanchor","");
if (href.indexOf('?') == -1) {
href = href + '?x='
} else {
href = href + '&x='
}
href = href + window.pageXOffset;
href = href + '&y=' + window.pageYOffset;
$(this).attr('href', href);
});
});
}
A couple of helper methods:
一些辅助方法:
function RestoreScrollPosition() {
var scrollX = gup('x');
var scrollY = gup('y');
if (scrollX != null && scrollY != null) {
window.scrollTo(scrollX, scrollY);
return true;
}
return false;
}
function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
This fits my needs, but could be more generic/reusable - I'd be happy for someone to improve on this... :-)
这符合我的需求,但可以更通用/可重用——我很高兴有人能在这方面做出改进……:-)
#9
0
a very not-nice way to do this is using cookies.
一种不太好的方法是使用cookie。
If you use ONE page in your MVC which handles the other pages you could a code-snippet to it that loads every page which creates a cookie (if non-existent) called "scrolltop". There are ways to have javascript automatically update this cookie when the user scrolls up or down by catching these events or watching the scrollTop value.
如果您在MVC中使用一个页面来处理其他页面,那么您可以使用一个代码段来加载每个页面,这些页面会创建一个名为“scrolltop”的cookie(如果不存在的话)。通过捕获这些事件或查看scrollTop值,可以让javascript在用户向上或向下滚动时自动更新此cookie。
On a new page you just have to load the saved position and make the view scroll there in 0 milliseconds (with Mootools or any Ajax script this should be possible) and the user will be exactly where they were.
在一个新页面上,您只需加载保存的位置,并使视图在0毫秒内滚动到那里(使用Mootools或任何Ajax脚本都可以),用户就会在它们所在的位置。
I don't know much about asp so I don't know if a method exists to anchor to a current y-position. Javascript is a fast and easy way. Anchors in HTMl could be an option if you had every element anchored and posted the anchor to other pages.
我不太了解asp,所以我不知道是否存在一个方法来固定到当前的y位置。Javascript是一种快速简单的方法。如果每个元素都被锚定并将锚点发布到其他页面,那么可以使用HTMl中的锚点。
#10
0
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):
我使用如下所示的.scrollTop,非常简单,它甚至可以处理视图中的多种形式(我有一个很长的视图,可以分解成多种形式):
First put this property inside the model:
首先将该属性放入模型中:
public string scrollTop { get; set; }
And in the view, inside Form #1:
在视图内,表单#1:
@Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm1"})
inside Form #2:
内部形式# 2:
@Html.HiddenFor(m => m.scrollTop, new {@id="ScrollForm2"})
inside Form #2:
内部形式# 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.
您的滚动位置总是在回发后保留,因为@Html。HiddenFor字段存储当前滚动并将其传递给post上的模型。然后,当页面出现时,它从模型中获取scrollTop值。最后你的页面会表现得像webform,一切都保持原样。
#11
-1
@{
}
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var div = document.getElementById("dvScroll");
var div_position = document.getElementById("div_position");
var position = parseInt(@Request.Form("div_position"));
if (isNaN(position)) {
position = 0;
}
div.scrollTop = position;
div.onscroll = function () {
div_position.value = div.scrollTop;
};
};
</script>
</head>
<body>
<div id="dvScroll" style="overflow-y: scroll; height: 260px; width: 300px">
1. This is a sample text
<br />
2. This is a sample text
<br />
3. This is a sample text
<br />
4. This is a sample text
<br />
5. This is a sample text
<br />
6. This is a sample text
<br />
7. This is a sample text
<br />
8. This is a sample text
<br />
9. This is a sample text
<br />
10. This is a sample text
<br />
11. This is a sample text
<br />
12. This is a sample text
<br />
13. This is a sample text
<br />
14. This is a sample text
<br />
15. This is a sample text
<br />
16. This is a sample text
<br />
17. This is a sample text
<br />
18. This is a sample text
<br />
19. This is a sample text
<br />
20. This is a sample text
<br />
21. This is a sample text
<br />
22. This is a sample text
<br />
23. This is a sample text
<br />
24. This is a sample text
<br />
25. This is a sample text
<br />
</div>
<hr />
<form method="post">
<input type="hidden" id="div_position" name="div_position" />
<input type="submit" value="Cool" />
</form>
</body>
</html>
You can use this to maintain scroll Position after postback.
在回发后,您可以使用它来保持滚动位置。
Source: http://www.aspsnippets.com/Articles/Maintain-Scroll-Position-of-DIV-on-PostBack-in-ASPNet.aspx
来源:http://www.aspsnippets.com/Articles/Maintain-Scroll-Position-of-DIV-on-PostBack-in-ASPNet.aspx