C# 如何清除视图状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2314204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear Viewstate?
提问by ryudice
I am having a problem in which two controls which are added programmatically are trying to load each other viewstate, I want to clear the viewstate before loading the controls, I tried Viewstate.Clear but it did nothing, when I disable viewstate on the container of my controls everything works fine except that the control's state is not kept. Is there a way to clear viewstate of just a specific control?
我遇到了一个问题,其中以编程方式添加的两个控件正在尝试加载彼此的视图状态,我想在加载控件之前清除视图状态,我尝试了 Viewstate.Clear 但它什么也没做,当我禁用容器上的视图状态时我的控件一切正常,只是没有保留控件的状态。有没有办法清除特定控件的视图状态?
采纳答案by slugster
From your description, it would seem that you are making one of the common mistakes when loading your dynamic controls - either you are loading them too late or you are not assigning them unique IDs (and assigning them the same unique id each time a postback occurs).
从您的描述来看,您似乎在加载动态控件时犯了一个常见错误 - 要么加载得太晚,要么没有为它们分配唯一 ID(并在每次回发时为它们分配相同的唯一 ID))。
If this is indeed your problem, then clearing the viewstate is not the appropriate action to be taking. It is quite simple to fix, check these three links:
如果这确实是您的问题,那么清除视图状态不是要采取的适当措施。修复很简单,检查这三个链接:
http://msdn.microsoft.com/en-us/library/ms972976.aspx
http://msdn.microsoft.com/en-us/library/ms972976.aspx
http://www.4guysfromrolla.com/articles/092904-1.aspx
http://www.4guysfromrolla.com/articles/092904-1.aspx
http://geekswithblogs.net/shahed/archive/2008/06/26/123391.aspx
http://geekswithblogs.net/shahed/archive/2008/06/26/123391.aspx
回答by Yuriy Faktorovich
Assuming both controls inherit from System.Web.UI.Control. You can disable their individual ViewStates by setting their EnableViewStateto false. Also you can clear their ViewState, as each control has a ViewStateproperty.
假设两个控件都继承自System.Web.UI.Control。您可以通过将它们的EnableViewState设置为 false来禁用它们各自的 ViewState 。您也可以清除它们的 ViewState,因为每个控件都有一个ViewState属性。
回答by Jeff Siver
Make sure the id's of the two programmatically added controls are different and the ViewState problem should go away.
确保两个以编程方式添加的控件的 id 不同,并且 ViewState 问题应该消失。
回答by Luhmann
You can disable viewstate on a specific control:
您可以在特定控件上禁用视图状态:
EnableViewState="False"
回答by cpkilekofp
Yes ,
是的 ,
string controlName = "name of control";
ViewState[controlName] = null;
// create control, add it to the page
回答by Rune
If ViewState gets in your way and you haven't done so already, please read
如果 ViewState 妨碍了您并且您还没有这样做,请阅读
It will make you much more comfortable in working with ViewState and the whole ASP.NET page lifecycle.
它将让您更轻松地使用 ViewState 和整个 ASP.NET 页面生命周期。