Retaining Anchor Position on ASP.NET Postback
I ran into a small problem the other day that although annoying, proved easy enough to fix. The problem arose because I was using JQuery UI tabs to allow multiple pageable gridviews to be managed on the one page. Whenever the gridview was paged a postback was initiated and the gridview paged as expected, however the selected tab state was not maintained.
This is because .NET posts back on the same url, including the querystring…but not associated anchors. This does make sence because the postback url is set when the page is rendered on the server.
The solution was to register a small piece of javascript in my gridview’s pagechanged event handler that sets the browser’s anchor location.
1 2 | Page.ClientScript.RegisterStartupScript( this.GetType(), "anchor", "location.hash = '#yourtab';", true); |
Tagged as anchor, ASP.NET, C#, postback + Categorized as ASP.NET, C#
This is sort of the same as MaintainScrollPositionOnPostback=”true” (added in the page directive), which maintains the scroll position on postback
Not sure if it would work with what you are doing though, as it sounds like you explicitly need the anchors in the URL?
Yea Darren, I explicitly needed the anchors in order for JQuery tabs to function properly. MaintainScrollPositionOnPostback does not know anything about the anchors, which JQuery is using to model the tabs.
Awesome!
I just ran into this today and this was a great fix! I had a form inside the tab in my case, but the snippet you gave also works in an OnClick handler as well.
Thanks again.
Thx!
This is very helpful!
Thanks William!
Your solution worked great.
I’d like to add something to it if I might though.
I found that after implementing that solution, after the page posted back, the text on the first tab was displayed for a split second before it switched to the current tab.
I was able to get around this by doing the following.
Put everything inside a <div> with hidden visibility.
Then, when the body is loaded, call a function which makes this visible.
function ShowMain()
{
var dvMain = document.getElementById(’dvMain’);
dvMain.style.visibility = ‘visible’;
}
Thank ClusterOfCephalopods. Your right, if the page has a lot of tabs and data it can take a while for the jQuery .ready event to run. Your solution should sort that.
Thanks.
* This save the integration (jquery + tabs + forms) in WebForms application.
Put the inside of your tab in asp update panel….
Your grid or whatever doing postback
thanks works for me.
Cheers buddy