Conditionally reset scroll position on a partial postback.


Here’s how to conditionally reset the browser’s scroll position of an ASP.NET page after an AJAX partial postback. You will of course need to have your web application ASP.NET Ajax ready.

Here’s the code. The following constant is the key that is sent by the server to the client browser after a postback. If this key is found by the client, the JavaScript function will tell the browser to reset the scroll position.

Private Const KEY As String = "ResetScrollPosition"

Here’s the page load event handler. In this event, you need to generate some JavaScript that contains the logic that tells the client browser how to reset the browser’s scroll position. This code basically consumes the data sent from the server, determines what data item was registered for the call along with its value. If that value contains the key constant, the browser will reset its scroll position.

Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) _
	Handles Me.Load
	
	Dim sBlock as string = "Reset"

	If Not Page.ClientScript.IsStartupScriptRegistered(sBlock) Then

 		Dim JS As StringBuilder = New StringBuilder("")
		Dim clientID as string = Page.ClientID		

                JS.Append("Sys.WebForms.PageRequestManager.getInstance()")
		JS.Append(".add_endRequest(endRequestHandler);")
                JS.Append(System.Environment.NewLine)
                JS.Append("function endRequestHandler(sender, args)")
                JS.Append(System.Environment.NewLine)
                JS.Append("{")
                JS.Append(System.Environment.NewLine)
                JS.Append("if (args.get_dataItems()['" + clientID + "']")
		JS.Append(" != undefined)")
                JS.Append(System.Environment.NewLine)
                JS.Append("{")
                JS.Append(System.Environment.NewLine)
                JS.Append("if (args.get_dataItems()['" + clientID + "']")
		JS.Append(" == '" + KEY + "')")
                JS.Append(System.Environment.NewLine)
                JS.Append("{")
                JS.Append(System.Environment.NewLine)
                JS.Append("self.scrollTo(0, 0);")
                JS.Append(System.Environment.NewLine)
                JS.Append("}")
                JS.Append(System.Environment.NewLine)
                JS.Append("}")
                JS.Append(System.Environment.NewLine)
                JS.Append("}")

                Page.ClientScript.RegisterStartupScript(Page.GetType(), _
			sBlock, _
			JS.ToString(), _
			True)

	End If

End Sub

So... how do we send the key to tell the browser to reset the scroll position? First we need to initiate a partial postback (in this case it’s a button click) When a partial postback is initiated, a server side event is invoked and handled. This event handler checks a condition, and if the condition is true, the ASP.NET Ajax Data Item (in this case the page itself) gets sent back to client with the KEY value. In order for this to work, the control causing the partial postback event needs to be inside an update panel on the .aspx page in order for this work.

Here’s the vb.net code containing the event handler:

Private Sub oBtnClick(ByVal sender As Object, ByVal e As EventArgs) Handles oBtn.Click
	If (true) then
		ScriptManager.GetCurrent(Page).RegisterDataItem(Page, KEY)
	End if
End Sub

Here’s the markup code for the button instatiating the partial postback.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
	<ContentTemplate>
		<asp:Button ID="oBtn" Text="Initiate Partial Postback" runat="server" />
	</ContentTemplate>
</asp:UpdatePanel>

This code can also serve as a base for anyone who wants to send statements back to a JavaScript function conditionally.

Tags: ,
Categories: ASP.NET Ajax | ASP.NET

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (23) Post RSSRSS comment feed

Comments

8/18/2010 11:34:26 AM #

Outdoor Garden Fountains

A very interesting view on this you have, really. I don't know what else to say. Keep it up.

Outdoor Garden Fountains United States

8/19/2010 12:51:06 AM #

blog

heißer Chat vor der Cam

blog Germany

8/19/2010 6:45:55 PM #

ffxiv gil

The Kreg Jig takes advantage of a technique called Kreg Joinery. Unlike other techniques, Kreg Jig requires no glue, no complicated math, and no small army of clamps to make wood joints that will last.<br />http://www.ffxivgilsaler.com/

ffxiv gil Uzbekistan

8/19/2010 7:25:18 PM #

cruel thing

Your blog is outrageous!  I mean, Ive never been so entertained by anything in my life!  Your vids are perfect for this.  I mean, how did you manage to find something that matches your style of writing so well?  Im really happy I started reading this today.  Youve got a follower in me for sure!<br />http://www.ikudian.com

cruel thing Faroe Islands

8/19/2010 8:25:34 PM #

wowgold

Dude, that's great! I'll be back for you new posts!<br />http://www.deliciousgold.com/

wowgold U.A.E.

8/20/2010 9:36:57 PM #

wow Hunter

Whether you are in the classroom or conference room, the sleek, contemporary design and rugged functionality of the 3M Overhead Projector Model 1711 means you can expand their minds without sacrificing your budget. An open singlet projection head makes the 3M Model 1711 easy to focus and clean, while 2,500 lumens of light ensure your image and message are clear - even when the room lights are on.<br />http://www.wow-hunters.com

wow Hunter Georgia

8/20/2010 10:22:46 PM #

nike shoes

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.<br />http://www.nikeshoesaler.com/

nike shoes Finland

8/22/2010 1:13:38 AM #

cross pen sets

Hey great blog, im glad you shared this topic and im even more glad with the comments! Keep it up everyone!

cross pen sets United States

8/23/2010 8:40:07 PM #

fetischlatex

Früher undenkbar, heute zu Hause in vielen Schlafzimmern: Reizwäsche aus geilem Gummi, Lack oder Leder. Da wird jeder Mann zum Tier.

fetischlatex Germany

8/24/2010 10:15:00 PM #

pondless water feature

hey, nice place ya got here.

pondless water feature United States

8/25/2010 9:41:01 AM #

cross pen refills

Great info here, thanks for sharing Smile.

cross pen refills United States

8/26/2010 5:25:25 AM #

nail polish sets

Hey great blog, im glad you shared this topic and im even more glad with the comments! Keep it up everyone!

nail polish sets United States

8/28/2010 4:26:44 PM #

game store

Please fix your RSS Feed, I Can not open with my opera browser, Anyway.. Your Post is very interested.. Good Job<br />http://www.gameoole.com

game store Russia

8/28/2010 6:20:32 PM #

ff14 gil

Me encontr&#233; con este post haciendo una investigaci&#243;n para mi universidad. Tengo que decir que suena como una persona muy alegre y espero alg&#250;n d&#237;a ser capaz de escribir tan bien como usted. Siempre he envidiado las personas que pueden escribir con pasi&#243;n y realmente dio en el clavo.<br />http://www.gil4ff14.com/

ff14 gil Oman

8/29/2010 5:46:41 AM #

collapsible water bottles

Great info here, thanks for sharing Smile.

collapsible water bottles United States

8/31/2010 7:23:29 AM #

nail polish storage

Hey great blog, im glad you shared this topic and im even more glad with the comments! Keep it up everyone!

nail polish storage United States

8/31/2010 8:35:57 AM #

swim spa pools


I just visited this page trough my iphone and the page messed up a bit for me, just to let the admin know. Anyway keep up the good work.

swim spa pools United States

8/31/2010 8:38:14 AM #

turquoise earrings

So great , I like it

turquoise earrings United States

8/31/2010 4:23:08 PM #

webcamsex kostenlos

guten tag... geilen webcamsex gibts hier.

webcamsex kostenlos Germany

9/5/2010 2:00:44 PM #

First Person Shooting

Excellent post I must say.. Simple but yet interesting and engaging.. Keep up the awesome work!<br />http://www.small-game-online.com

First Person Shooting Estonia

9/5/2010 3:08:36 PM #

ffxiv gold

Hmmm interesting stuff<br />http://www.ffxivgoldonline.com/

ffxiv gold Puerto Rico

9/6/2010 8:05:46 AM #

motorola bluetooth wireless headset

It is very useful to me. thank you!

motorola bluetooth wireless headset United States

9/6/2010 8:06:46 AM #

nfl women apparel

I have searched this information for a long time.

nfl women apparel United States

Add comment


(Will show your Gravatar icon)
  Country flag

biuquote
  • Comment
  • Preview
Loading