How do I maintain scroll position in MVC?
The way MaintainScrollPositionOnPostback works is that it has a pair of hidden fields:
__SCROLLPOSITIONX and __SCROLLPOSITIONY
On a postback, it sets these,
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
}
else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
}
else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
}
else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
and then it calls RestoreScrollPosition:
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
}
else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
But as most people said, MVC should be avoiding postbacks anyway.
How do you maintain the previous scroll position after post using asp.net core 3.1 MVC and razor views?
First, Create a base view model that all other models will inherit
public class BaseViewModel
{
public int ScrollPosition { get; set; }
}
All view models that are bound that will need to remember the previous scroll position will inherit from this BaseViewModel
Second, Add a hidden input to your form used for posting:
@using(Html.BeginForm("SomeAction", "SomeController", FormMethod.Post)
{
@Html.HiddenFor(x => Model.ScrollPosition)
....
}
Third, inside your post method on the backend set a value to TempData
:
TempData["ScrollPosition"] = Model.ScrollPosition;
Fourth, when redirect after post, set this value to your Model for binding in your view:
MyModel.ScrollPosition = (int)TempData["ScrollPosition"];
Fifth, use javascript to scroll to previous position after page load:
<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>
If you would need to track x axis scroll as well as y axis, you'd need two hidden inputs
for each x and y axis scroll position and change model to hold both x and y
How to set scroll position in MVC 4 when new page is loaded
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:
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 preferOn the Controller
TempData["scrollTo"] = position; //where position is the param you received from the view
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>
}
ASP.NET MVC3 Razor - Maintain scroll position on postback
The usual way is to use some javascript to set the current scroll position to a hidden field, then restore that position on page load (usually in a jquery ready event).
However, that's really just a side effect. You should be doing some kind of ajax command to update the grid rather than a postback, then no scrolling required.
How to maintain scroll position when using HTML.ActionLink in MVC Asp.Net?
You can name the anchor tag and refer to the name in the href
using the hash notation:
<a href="@Url.Action("Approve", new { id = item.Id })" id="@( item.Id )" name="@( item.Id )">Approve</a>
And then in your action method:
string redirectUrl =
string.Format(
"{0}#{1}",
Url.Action("Index"),
id);
return new RedirectResult(redirectUrl);
Just make sure your id
is a value HTML id
(nearly anything can be a valid id
in HTML5, however rules apply for the naming of ids
for earlier HTML versions). If in doubt, prefix it with something like 'aid-' (approval id), etc. before using in the HTML.
Otherwise, like you've already identified, your best bet is to use an AJAX call to make the approval. This way you stay exactly where you are on the page.
Keep scroll position after Postback - 2019
For future reference.
My problem resided in the code itself, using Control.Focus() "conflits" with the Scroll position.
As @GaganDeep helpfully explained, one cannot use Control.Focus() and MaintainScrollPositionOnPostback="true" and the same time, as the Focus() Scrolls the page to the position of the referenced Control.
Thank you for your help! I was really struggling with this one, never thought it could be such a "simple" thing.
Set page scroll position on page load of MVC view with javascript
In your example nothing can be scrolled anyway because everything is in the visible area. Apart from that mituw16 already gave you the right solution. Here is an example how to use the scrollIntoView function.
<script type="text/javascript"> function scrollToImportantStuff() { document.getElementById('ImportantStuff').scrollIntoView() } window.onload = scrollToImportantStuff;</script> <h2> TITLE OF THE VIEW <h2>
<input type="button" onclick="document.getElementById('ImportantStuff').scrollIntoView()" value="Scroll ImportantStuff into View" />
<div style="height:500px;"> Lots of content here </div>
<div style="height:500px;"> Even more content here </div>
<div id="ImportantStuff"> Important stuff here </div>
Easy way to maintain scroll position with ASP.NET MVC2?
Sorry - there's nothing built into MVC - you need javascript
Related Topics
How to Embed a Google Drive Folder in a Website
Relative Url to a Different Port Number in a Hyperlink
5 Images Symmetrically Seperated with Diagonal Lines
How to Notify the HTML Container That the Swf Has Finished, Using Swfobject
Html-Tooltip Position Relative to Mouse Pointer
Margin:Auto;' Doesn't Work on Inline-Block Elements
Why My Inline-Block Divs Are Not Aligned When Only One of Them Has Text
Why Is Nth-Child Selector Not Working
Make <Body> Fill Entire Screen
How to Make Div's Percentage Width Relative to Parent Div and Not Viewport
Why Does My Transform Snap Back
HTML Combo Box with Option to Type an Entry
Using .Otf Fonts on Web Browsers
Center HTML Input Text Field Placeholder
Remove Background Arrow from Date Input in Google Chrome V20
Auto Height on Parent Container with Absolute/Fixed Children