3

Using the below code to retain screen position

<script type="text/javascript">
    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
    function BeginRequestHandler(sender, args) {
        xPos = $get('#UpdatePanel_1').scrollLeft;
        yPos = $get('#UpdatePanel_1').scrollTop;
    }
    function EndRequestHandler(sender, args) {
        $get('#UpdatePanel_1').scrollLeft = xPos;
        $get('#UpdatePanel_1').scrollTop = yPos;
    }
</script>

as described in the below link https://weblogs.asp.net/andrewfrederick/maintain-scroll-position-after-asynchronous-postback

but after using the above code my code behind actions stops working.

Any suggestion will be highly helpful.

ASPX Code

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" MaintainScrollPositionOnPostback="True" %>
<%--<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.19.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>--%>

<link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
     <asp:ScriptManager ID="ScriptManager1" runat="server" />

    <script type="text/javascript">
        var xPos, yPos;
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);
        function BeginRequestHandler(sender, args) {
            xPos = $get('divScroll').scrollLeft;
            yPos = $get('divScroll').scrollTop;
        }
        function EndRequestHandler(sender, args) {
            $get('divScroll').scrollLeft = xPos;
            $get('divScroll').scrollTop = yPos;
        }
    </script>


   <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel_1">
    <ProgressTemplate>
        <div class="modal_1">
            <div class="center">
                <img alt="" src="Loader.gif" />
            </div>
        </div>
        </ProgressTemplate>
    </asp:UpdateProgress>

        <asp:UpdatePanel runat="server" ID="UpdatePanel_1">
            <ContentTemplate>
                <div class="divScroll">
                <div class="container">
                    <div class="row">
                        <div class="col-md-3">   
                            <div class="CustomDiv">     
                                Gender
                            </div>
                        </div>

                        <div class="col-md-3">  
                            <div class="CustomDiv">           
                                <asp:TextBox ID="txtGender" runat="server" Height="40px" Width="100%"></asp:TextBox>
                            </div>
                        </div>
    
                        <div class="col-md-3">   
                            <div class="">                
                                <asp:CheckBox ID="chkNotKnown" runat="server" AutoPostBack="True" Text="&nbsp;&nbsp;(Not Known)" Font-Bold="False" />
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="cssErrorMsg">                
                                <asp:RequiredFieldValidator ID="rfvGender" runat="server" 
                                    ControlToValidate="txtGender" ErrorMessage="Gender Required" 
                                    InitialValue="" BackColor="Yellow"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                    </div>
                </div>
                </div>
            
            </ContentTemplate>
                <Triggers>
                    <%--<asp:PostBackTrigger ControlID = "txtGender" />--%>
                </Triggers>
        </asp:UpdatePanel>

</div>
</form>

Vb.Net Code

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub chkNotKnown_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkNotKnown.CheckedChanged

    With txtGender
        If chkNotKnown.Checked Then
            .Text = "Not Known"
            .Enabled = False
        Else
            .Text = ""
            .Enabled = True
        End If
        .Focus()
    End With
End Sub
End Class

I have several controls which retrieves the data from server but I just shown a simple code behind example for reference.

Commenting / Removing the above JS will let the code behind action to run. Otherwise cliking the chkNotKnown check box will not fire the event.

Feedback 1

Tried all the suggestions and still the JS code is not retaining the screen position. I wonder how it is working for others in the provided link :(.

Feedback 2

Finally I ended using the below JS

In ASPX Code Page

<script type="text/javascript">  
var xPos, yPos, needScroll;  
var prm = Sys.WebForms.PageRequestManager.getInstance();  
prm.add_beginRequest(BeginRequestHandler);  
prm.add_pageLoaded(EndRequestHandler)  

function BeginRequestHandler(sender, args) {  
    xPos = 0;  
    yPos = window.pageYOffset || document.documentElement.scrollTop;  
}  

function EndRequestHandler(sender, args) {  
    if (needScroll) {  
        window.setTimeout("window.scrollTo(" + xPos + "," + yPos + ")", 100);  
    }  
}  
</script>  

In Code Behind Page Load Event

ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType(), "ScrollTo", "var needScroll = true;", True)

Source Link

https://www.c-sharpcorner.com/blogs/maintain-or-set-page-scroll-position-after-asynchronous-postback-in-asp-net-ajax

Sixthsense
  • 1,927
  • 2
  • 16
  • 38
  • Are there any errors in the browser's development console? Focusing on any one specific "code behind action" which "stops working", how specifically do you invoke it and how specifically does it fail? Do the browser's debugging tools tell you anything? – David Jan 10 '23 at 11:44
  • All the controls code behind action works fine if I remove or comment the above given JS. No errors and no notification and simply the code behind actions didn't fire at all. – Sixthsense Jan 10 '23 at 11:48
  • that example assumes a gv inside of a update panel. In most cases, I would add a data pager to the gv, and thus eliminate the issue of scrolling anyway. However, you might have to post more markup, as it not clear your setup you have. – Albert D. Kallal Jan 10 '23 at 17:34
  • Updated the question with sample html and code behind actions. Please suggest – Sixthsense Jan 12 '23 at 07:46
  • @Sixthsense have you able to fix this issue ? or you can just use JS code block after Document.ready I guess – Anant Dabhi Jan 18 '23 at 08:24
  • Thanks to all for your suggestion. But still the JS is not holding the current screen position after trying all suggestions. The screen reacts in the same way when I don't have JS. – Sixthsense Jan 20 '23 at 10:46

3 Answers3

1

NOTE: In your code there are two different BeginRequestHandler function,

  1. on top you are using update panel id and
function BeginRequestHandler(sender, args) {
    xPos = $get('#UpdatePanel_1').scrollLeft;
    yPos = $get('#UpdatePanel_1').scrollTop;
}
  1. on bottom code you are using div class name.
function BeginRequestHandler(sender, args) {
    xPos = $get('divScroll').scrollLeft;
    yPos = $get('divScroll').scrollTop;
}

What's the Issue:

It shows the error as Cannot read properties of null (reading 'scrollLeft')

Issue Reason:

id used for variable xPos and yPos returns null.

Solution 1:

If you want to use update panel id then try this

Remove # from ID start:

$get('#UpdatePanel_1').scrollLeft;

Use it like this:

$get('UpdatePanel_1').scrollLeft;

Solution 2:

If you want to use div id then try this

Add id to your div.

HTML:

<div class="divScroll" id="divScroll">

JavaScript:

function BeginRequestHandler(sender, args) {
    xPos = $get('divScroll').scrollLeft;
    yPos = $get('divScroll').scrollTop;
}
Muthu
  • 73
  • 1
  • 10
0

As you mentioned that your code behind action is not working after adding JS code. possible cause are:

1.Use js code block that execute after document ready 2.$get will not work for searching element use $("#ID") or javascript 'document.getElementById'

 <script type="text/javascript">
        var xPos, yPos;
      $( document ).ready(function() {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);
      });
        function BeginRequestHandler(sender, args) {
            xPos = document.getElementById('divScroll').scrollLeft;
            yPos = document.getElementById('#divScroll').scrollTop;
        }
        function EndRequestHandler(sender, args) {
            document.getElementById('#divScroll').scrollLeft = xPos;
            document.getElementById('#divScroll').scrollTop = yPos;
        }
    </script>
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
0

Please, add the attribute ClientIdMode of your Update Panel like this:

<asp:UpdatePanel runat="server" ID="UpdatePanel_1" ClientIdMode="Static">

If you don't do this, the Asp.NET Web Forms add a dynamic suffix like as a GUID number into the ID attribute value, and your JavaScript code never recognizes the rendered HTML ID attribute value #UpdatePanel_1

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Antonio Leonardo
  • 1,805
  • 1
  • 8
  • 18
  • Whether you tried this? Its not working for me. Even though I used ClientIdMode="Static" still code behind not called. – Muthu Jan 18 '23 at 20:01
  • Please, now, try to add your JavaScript code inner `$(document).ready(function() { //your code will be here });` scope. – Antonio Leonardo Jan 18 '23 at 20:35
  • No that's not the issue here. I've found the issue and posted it in answer. What's the OP issue is `#` used at beginning of `update panel id` and inside code another *BeginRequestHandler* used in that instead of *div id*, `div class name` used. I think these are the issues. – Muthu Jan 18 '23 at 20:47