如何在使用核心 3.1 MVC 和剃须刀视图发布后保持 asp.net 滚动位置?



如何使用 asp.net 核心 3.1 MVC(Web 应用程序)和 razor 视图在帖子后保持之前的滚动位置?

您如何在整个网站上执行此操作?

我看到了这个:ASP.NET MVC3 Razor - 在回发时保持滚动位置 - 但这些对我不起作用。

首先,创建一个所有其他模型都将继承的基本视图模型

public class BaseViewModel
{
public int ScrollPosition { get; set; }
}

绑定的所有需要记住上一个滚动位置的视图模型都将继承自此基本视图模型

其次,在用于发布的表单中添加隐藏输入:

@using(Html.BeginForm("SomeAction", "SomeController", FormMethod.Post)
{
@Html.HiddenFor(x => Model.ScrollPosition)
....
}

第三,在后端的 post 方法中设置一个值TempData

TempData["ScrollPosition"] = Model.ScrollPosition;

第四,在发布后重定向时,将此值设置为模型以在视图中绑定:

MyModel.ScrollPosition = (int)TempData["ScrollPosition"];

第五,页面加载后使用 javascript 滚动到上一个位置:

<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function(){
//add event listener for the scroll event and set hidden input value for posts
document.addEventListener('scroll', function(){
const scrollPosY = window.scrollY;
document.querySelector('input[name="ScrollPosition"]').value = scrollPosY;
});
const scrollpos = document.querySelector('input[name="ScrollPosition"]').value;
window.scrollTo(0, scrollpos); //y-axis scroll
});
</script>

如果您需要跟踪 x 轴滚动和 y 轴,则需要两个隐藏输入 对于每个 x 和 y 轴滚动位置并更改模型以同时容纳 x 和 y

另一种方法是使用 AJAX 提交表单,并在成功开机自检后调用window.location.reload();这将恢复滚动位置。

function CreateItem() {
var serializedForm = $('#formId').serialize();
$.ajax({
url: "item/create",
type: "POST",
data: serializedForm
})
.done(function () {
window.location.reload();
});
}

首先在脚本标记中将以下 jquery 函数添加到您的页面:

$(document).scroll(function () {
// Note scroll position.
localStorage['pageIdentifier'] = $(document).scrollTop();
});

然后添加:

$(document).ready(function () {
// Maintain scroll position.
$(document).scrollTop(localStorage['healthPage']);
});

最新更新