Search code examples
javascriptasp.net-mvcasp.net-mvc-4scroll-position

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


In my MVC 4 Webapp one of the views is listing house objects, and to the right of every object the user has the possibility to change language. Let's say you are on the middle of the page Reading about an object and decides you want to change language. Then a new page is loaded which looks exactly the same, but with text now in the other language. The problem is that the new page starts from the beginning (of course since it's a new page), and I want the newly loaded page to have the same scroll position as the previous one.

To get a better understanding you can visit the site at http://www.lomahovi.com and then click on Accomodations. There you will see a link for every object where you can switch between English and Russian.

So if a client is looking at an object in English, and decides that he/she wants to switch to Russian I don't want the page to start at the beginning but instead it should be on the same object/position as it was in English, so that the client doesn't have to scroll down the page to find the object again.

Any help is appreciated. Thanks,

Peter


Solution

  • You can send back to the controller which change language the current screen position - something like this--> Link

    Store the result into a temp object (i.e. TempData ["scrollTo"]).

    On your view, check is TempData["scrollTo"] is not null, if not, navigate to that position (with jquery)

    Edit:

    Something like this:

    1. On the View: (bind it with your language click)

      var screenTopPosition = $(document).scrollTop();
      //--Send this var to your controller as url param or w/e you prefer
      
    2. On the Controller

      TempData["scrollTo"] = position; //where position is the param you received from the view
      
    3. And again on the view:(with Razor)

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

    Added:

    To send the java-script var using the Html Helper you need something like this (the view):

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