如何与JavaScript共享一个C#Integer变量 [英] How to share a C# Integer variable with JavaScript
问题描述
我想用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;
//在(index)
显示选项卡
我使用这种方法在PostBack上再次获取当前选项卡。但是,C#上的 currentTab
在 PostBack
之后仍然是 1
。我可以如何解决这个问题?
您可以将您的javascript函数的索引写入隐藏字段,然后阅读在回发中。
在您的代码中,您检查隐藏字段,如果您的页面是回发。
像这样:
protected void Page_Load(object sender,EventArgs e)
{
if(Page.IsPostBack)
{
currentTab = Int32.Parse(HiddenTabValue.Value);
}
}
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?
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);
}
}
这篇关于如何与JavaScript共享一个C#Integer变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!