问题
I have a aspx page which has three tabs. When I click a button in tab3, a postback will occur and it will bring me back to the tab1. How do I stay in the tab3? Following is my aspx page. Also I have noticed we have a javascript to set the active tab to tab1. Can anyone tell me how to modify it so that it will set the selected tab as the active tab during a postback?
<script type="text/javascript">
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
<div id="content">
<ul class="tabs">
<li><a href="#tab1">Edit</a></li>
<li><a href="#tab2">History</a></li>
<li><a href="#attachmentcontent">Attachments</a></li>
</ul>
<div class="tab_container">
<div id="tab1" class="tab_content">
...
回答1:
What you're referring to is maintaining state, common approaches would be store a variable in the session or viewstate indicating what is the 'selected' tab. Then on page load read that back and apply it to your page in the appropriate location.
回答2:
Keep a session value of tab 3 and during a postback just set the tab position to that session value.
Basically you need to store the state somewhere, whether it is some cookie / session state is completly up to you. Then you load that session state variable into your control's property value to set it back to the position you were looking at.
Read up on asp.net session state.
回答3:
The session has some drawbacks. JavaScript can only read the first value of session. For example, you set Session["name"]="Gaolai Peng" in Page_Load. Then in a button click's post back, if you set Session["name"]="Rauf". If you read the session using JavaScript it will return "Gaolai Peng". So please use HiddenField instead of session.
回答4:
Use PostBackUrl property and set it /#<your tabID>
example:
PostBackUrl = "/#tab1"
来源:https://stackoverflow.com/questions/7715366/how-do-i-stay-in-the-selected-tab-during-a-postback