Mark Highfield
Mark Highfield

Reputation: 453

Set Session variable and prevent postback on ASP.NET button click

I have an ASP button that, when clicked, needs to set a session variable and run some javascript code to pop up a window. I have this all working fine, however when this happens the main page does a postback and jumps back to the top of the page. How can I prevent the postback and still set the session variable and call the javascript? So that the main window stays in the same position?

Upvotes: 0

Views: 968

Answers (2)

Antonio Bakula
Antonio Bakula

Reputation: 20693

Do it with ajax, set ASP.NET button to run only on client, set onClient event to :

onclient="SetSession(); return false;"

and in SetSession() JavaScript function call server method, for example simple ashx, and if server call succeeded then you can call additional JavaScript you need. (using jQuery it's much easier) :

function SetSession()
{
  jQuery.ajax({
                url: "SetServerSideSession.ashx", 
                success: function (data) 
                {  
                  AdditionalJavascript();
                }
             });
}

Upvotes: 3

Morten Anderson
Morten Anderson

Reputation: 2321

To maintain same position after postback you can use Page.MaintainScrollPositionOnPostBack

Page.MaintainScrollPositionOnPostBack Property

Upvotes: 1

Related Questions