Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a C# Integer variable with JavaScript

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?

like image 622
Eng.Fouad Avatar asked Jan 25 '26 07:01

Eng.Fouad


2 Answers

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);
        }

    }
like image 149
Nicolai Avatar answered Jan 27 '26 20:01

Nicolai


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.

like image 28
Oded Avatar answered Jan 27 '26 21:01

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!