I want to share the currentTab variable which exists on the C# server side with JavaScript. Here is my code:
C#:
public int currentTab = 1;
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "showTab(" + currentTab + ");", true);
}
JavaScript:
var currentTab = "<%=currentTab%>";
function showTab(index)
{
currentTab = index;
// Show tab at (index)
}
I used this approach to get the current tab again on PostBack. However, currentTab on C# is remains 1 after PostBack. How can I solve this issue?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can write the index from your javascript function, to a hiddenfield, and then read that on postback.
In your code, you check the hiddenfield, if your page is postback.
Like so:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
currentTab = Int32.Parse(HiddenTabValue.Value);
}
}
Method 2
Have a server side hidden field to hold this piece of information.
You can access the field through javascript and as a server side control the value will be available server side.
Method 3
You need to use some server control to send value back to the server (i.e. asp:HiddenField) or use query string to set the tab index there.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0