我想用JavaScript共享C#服务器端存在的currentTab
变量。这是我的代码:
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)
}
我使用这种方法在PostBack上再次获取当前标签。但是,在currentTab
之后,C#上的1
仍为PostBack
。我该如何解决这个问题?
答案 0 :(得分:2)
您可以将javascript函数中的索引写入隐藏字段,然后在回发时读取该索引。
在您的代码中,如果您的页面是回发,则检查隐藏字段。 像这样:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
currentTab = Int32.Parse(HiddenTabValue.Value);
}
}
答案 1 :(得分:2)
让服务器端hidden field来保存这条信息。
您可以通过javascript访问该字段,并且作为服务器端控件,该值将在服务器端可用。
答案 2 :(得分:1)
您需要使用一些服务器控件将值发送回服务器(即asp:HiddenField
)或使用查询字符串在那里设置选项卡索引。