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:
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.