什么时候在viewstate中保存变量? [英] When to save a variable in viewstate?

查看:62
本文介绍了什么时候在viewstate中保存变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索了答案,发现大部分变量都保存在page.prerender事件的viewstate中.然后在页面加载事件中将变量的值重新设置.

但是,当我在prerender或load事件中将变量保存在viewstate中时,在代码隐藏中动态更改变量后,viewstate如何存储变量的值?

比方说,页面加载后,用户单击了一个按钮,该按钮在onClick事件中更改了变量的值.然后,自单击按钮以来引发了回发事件.据我说,如果仅在prerender事件中将变量保存在视图状态中,则新值应该已经丢失并且不能保存在视图状态中.因为回发时不会触发prerender事件,因此无法保存该值.

我不应该在回发事件发生之前将变量保存在viewstate中吗?

我错了吗?如果是这样,如果将viewstate保存在prerender事件中,则viewstate如何存储变量的新值?

谢谢您的回答.

解决方案

我怀疑您在保存ViewState时感到困惑.通过使用常规访问器方法实际修改该ViewState内存中对象,可以将内存中的ViewState集合序列化为字符串表示形式或可以轻松序列化的中间对象.

您可能会听到的是
(来源: microsoft.com )

I have searched the web for the answer and saw that mostly variables are saved in viewstate on page.prerender event. Then the value of the variable is set back in page load event.

However, when I save a variable in viewstate on prerender or load events, how can viewstate store the value of the variable after it is changed dynamically on codebehind?

Let's say, after page is loaded, user clicked a button which changes the value of the variable in its onClick event. Then the postback event raised since the button was clicked. According to me, the new value should have been lost and cannot be saved in the viewstate if the variable is saved in the viewstate only in prerender event. Because on postback the prerender event wont fire and the value cannot be saved.

Shouldn't I save the variable in the viewstate just before the postback event rises?

Am I wrong? If so, how can viewstate store the new value of the variable if the viewstate is saved in prerender event?

Thanks for the answer in advance..

解决方案

I suspect you're confusing saving ViewState, ie. serializing the ViewState collection in memory to a string representation or to an intermediate object that can be serialized easily, with actually modifying that ViewState in-memory object with its regular accessor methods.

What you may be hearing is that the SaveViewState() method is called after PreRender event. But that has little to do with when you get to modify the contents of the ViewState collection.

Checkout points 7. Prerender the Objects and 8. ViewState Saved in the article The ASP.NET Page Life Cycle. There's a good MSDN article that touches on this as well.


(source: microsoft.com)

这篇关于什么时候在viewstate中保存变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆