logo

ASP.NET MVC Version of MaintainScrollPositionOnPostback

In ASP.NET "classic" WebForms you can set the following property of a Page to make sure that users return to the place they were at following a "post back" for a form.

MaintainScrollPositionOnPostback="true"

In ASP.NET MVC this ability isn't built in. Here's how I built in my own version of it.

Let's say you have a big long form and near the bottom is a way to add multiple items, one at a time, using a simple field/button combination, like so:

<div id="AtBottomOfForm"> <p>Items added already: A1, B3, F5</p> <p>
<input name="AddItem" />
<input type="Submit" value="Add Item" />
</p>
</div>

Each time a user adds an item you want them to return to the same part of the form. To do this, in the Controller I added a property to the ViewBag object called "JumpTo". Like so:

ViewBag.JumpTo = "AtBottomOfForm";

In the View I then add this code:

image

This then generates the following JavaScript:

$(document).ready(function () {
   var JumpTo = 'AtBottomOfForm';
   if (JumpTo != "") {
      $(this).scrollTop($('#'+JumpTo).position().top);
   }
});

It should be fairly obvious what this does, how it works and that it relies on jQuery.

As I move from classic ASP.NET to MVC I'm finding a lot of the convenience methods such as this are no longer available. However, I'm also finding that it's easy to reproduce them in ways like this.

Comments

Hear that? Silence! Be the first to talk. Use the form below...

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:


About This Page

Written by Jake Howlett on Wed 27 Apr 2011

Share This Page

# ( ) '

Comments

No comments for this entry yet.

Skip to the comments or add your own.

You can subscribe to an individual RSS feed of comments on this entry.

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »

More Content