Search code examples
javascriptasp.netascx

How can I access a javascript variable from the codebehind of an ascx?


Specifically, I have an ascx control, let's assume it injects the javascript var x=5.

The ascx control contains a button, which when clicked does x++;

x is then 6.

When someone puts my control on their page, and clicks a button that posts back (the button is their own), I want to let them retrieve the value of x in the code behind.

Is there a solution that would allow this? The closest I can think of is to put a hidden field in the ascx, and store the value in the hidden field when it is updated. Then in my codebehind, on postback, I can do myControl.hiddenField.value to retrieve the result.

I haven't tried this yet as I am wondering if there is a better way. Also I'm not sure if the updated value of hidden field will register when it is altered via javascript, although being a post, I would hope it is.

Thoughts?

Edit: In fact, using a getter I could hide away the hidden field and just allow direct access to the value... if that solution is the best...


Solution

  • Yes, your own answer is the best one...especially with your edit! Form fields are how these two tiers communicate with one another. You could potentially invoke an ajax post with a some dynamically built get / post parameters, but this wouldn't be any better...