开发者

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

开发者 https://www.devze.com 2023-04-02 07:14 出处:网络
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++;

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 开发者_JAVA百科the value... if that solution is the best...


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...


Your idea is already the best approach you can take. I don't think you can go with the Ajax request option proposed by Timbo because yours is an ascx control that can be placed in many different forms and how would you determine were will you send the post or get request?

In conclusion, your approach is just fine and there's nothing inefficient with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消