小编典典

如何在MVC中保持滚动位置?

html

我正在MVC中从事一个项目,并且对此有所了解。有一些成长的烦恼,但一旦您找出来,那还不错。在WebForms世界中,真正简单的一件事是保持页面上的滚动位置。您所要做的只是将MaintenanceScrollPositionOnPostback属性设置为true。但是,在MVC中,我不使用回发,因此这对我不起作用。处理此问题的标准方法是什么?

编辑: Ajax是可以接受的,但我也想知道如果没有AJAX,您将如何做。


阅读 302

收藏
2020-05-10

共1个答案

小编典典

MaintenanceScrollPositionOnPostback的工作方式是它具有一对隐藏字段:__SCROLLPOSITIONX和__SCROLLPOSITIONY

在回发中,将这些设置为

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;
    }

然后调用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;
}

但是正如大多数人所说,MVC无论如何应避免回发。

2020-05-10