加载新页面时如何在 MVC 4 中设置滚动位置

How to set scroll position in MVC 4 when new page is loaded

在我的 MVC 4 Webapp 中,其中一个视图是列出房屋对象,并且在每个对象的右侧,用户可以更改语言。假设您在页面中间正在阅读一个对象并决定要更改语言。然后加载一个看起来完全相同的新页面,但文本现在是另一种语言。问题是新页面从头开始(当然既然是新页面),我希望新加载的页面与前一个页面具有相同的滚动位置。

要更好地了解,您可以访问位于 http://www.lomahovi.com 的网站,然后单击“住宿”。在那里你会看到每个对象都有一个 link,你可以在其中切换英语和俄语。

因此,如果客户正在查看英文对象,并决定 he/she 想要切换到俄语,我不希望页面从头开始,而是应该在同一位置object/position 因为它是英文的,所以客户不必向下滚动页面来再次找到该对象。

感谢任何帮助。 谢谢,

彼得

您可以将当前屏幕位置的语言发送回控制器 - 类似这样--> Link

将结果存储到临时对象中(即 TempData ["scrollTo"])。

根据您的看法,检查 TempData["scrollTo"] 是否不为空,如果不为空,请导航至该位置(使用 jquery)

编辑:

像这样:

  1. 在视图上:(将其与您的语言绑定点击)

    var screenTopPosition = $(document).scrollTop();
    //--Send this var to your controller as url param or w/e you prefer
    
  2. 在控制器上

    TempData["scrollTo"] = position; //where position is the param you received from the view
    
  3. 再次查看:(使用 Razor)

    $(function(){
       @if (TempData["scrollTo"]!=null)
      {
        var screenTop = @TempData["scrollTo"];
        $('#content').css('top', screenTop); //replace #content with your main div
      }
    });
    

已添加:

要使用 Html 助手发送 [​​=46=]-script 变量,您需要这样的东西(视图):

<div style="height:1000px">
    test
</div>
<div style="height:1000px">
    <a id="link" href="#">
        Click me
    </a>
</div>

@section scripts{
<script>

    var link = '@Url.Action("ActionName", "ControllerName", new { screenPosition = 123 })'

    $(function () {
             $("#link").click(RedirectWithScreenPos);
    });


    function RedirectWithScreenPos() {
        var screenPos = $(document).scrollTop();
        link = link.replace('123', screenPos);
        window.location.href = link;

    }
</script>
}