ASP.NET postbacks lose the hash in the URL

江枫思渺然 提交于 2019-12-04 03:07:32

The problem is that the postback goes to the url of the current page, which is set in the action of the form on the page. By default this url is without #hash in asp.net, and its automatically set by asp.net, you have no control over it.

You could add the #hash to the forms action attribute with javascript:

document.getElementById("aspnetForm").action += location.hash

or, if updating an action with a hash already in it:

var form = document.getElementById("aspnetForm");
form.action = form.action.split('#')[0] + location.hash

just make sure you execute this code on window.load and you target the right ID

Jesse Webb

I tried to put the code from Willem's answer into a JS function that got called everytime a new tab was activated. This didn't work because it kept appending an additional #hash part to the URL every time I switched tabs.

My URL ended up looking like http://myurl.example.com/home#tab1#tab2#tab3#tab2 (etc.)

I modified the code slightly to remove any existing #hash component from the URL in the <form> element's action attribute, before appending on the new one. It also uses jQuery to find the element.

$('.nav-tabs a').on('shown', function (e) {
    // ensure the browser URL properly reflects the active Tab
    window.location.hash = e.target.hash;

    // ensure ASP.NET postback comes back to correct tab
    var aspnetForm = $('#aspnetForm')[0];
    if (aspnetForm.action.indexOf('#') >= 0) {
        aspnetForm.action = aspnetForm.action.substr(0, aspnetForm.action.indexOf('#'));
    }
    aspnetForm.action += e.target.hash;
});

Hope this helps someone!

I have another solution, implemented and tested with chrome, IE and safari.

I am using the "localStorage" object and it suppose to work all the browsers which support localStorage.

On the click event of tab, I am storing the currentTab value to local storage.

$(document).ready(function() {
        jQuery('.ctabs .ctab-links a').on('click', function(e) {
            var currentAttrValue = jQuery(this).attr('href');
            localStorage["currentTab"] = currentAttrValue;

            // Show/Hide Tabs
            jQuery('.ctabs ' + currentAttrValue).show().siblings().hide();

            // Change/remove current tab to active
            jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

            e.preventDefault();
        });
        if (localStorage["currentTab"]) {
            // Show/Hide Tabs
            jQuery('.ctabs ' + localStorage["currentTab"]).show().siblings().hide();
            // Change/remove current tab to active
            jQuery('.ctabs .ctab-links a[href$="' + localStorage["currentTab"] + '"]').parent('li').addClass('active').siblings().removeClass('active');
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!