.net 回发后视图状态不会持续存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9802306/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:19:33  来源:igfitidea点击:

Viewstate does not persist after postback

.netvb.netviewstatepage-lifecycle

提问by ThdK

I'm having some problems in persisting the viewstate on postback for a Control (vb.net)

我在为控件(vb.net)在回发时保留视图状态时遇到了一些问题

here's some code i've put in my control:

这是我控制的一些代码:

Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
            MyBase.OnInit(e)
            Me.EnableViewState = True
            Me.ViewStateMode = System.Web.UI.ViewStateMode.Enabled
            If Not Page.IsPostBack Then
                _SortTime = DateTime.Now
                _SortTime.AddSeconds(-10) ' incase the fileserver and webserver date are out of sync
                ViewState("PageLoadTimeStamp") = _SortTime      
            End If
        End Sub

onload:

负载:

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        MyBase.OnLoad(e)

        _SortTime = CType(ViewState("PageLoadTimeStamp"), DateTime)

End Sub

But on every postback, the viewstate is empty again.

但是在每次回发时,视图状态再次为空。

Update: What do i want to do? I want to store the time when the user first loads the page. Then, the user will do multiple postbacks. On every postback i need to know that time.

更新:我想做什么?我想存储用户第一次加载页面的时间。然后,用户将进行多次回发。在每次回发时,我都需要知道那个时间。

Update 2:Context:

更新 2:上下文:

  • An aspx page (Editor.aspx) will load a web control (ObjectsEditor.ascx) dynamicly
  • ObjectsEditor.ascx contains of a single custom control (Objects.vb)
  • Objects.vb will create another custom control (ObjectsContainer.vb) and add it to it's controls It is the ObjectsContainer that needs to persist the viewstate.
  • aspx 页面 (Editor.aspx) 将动态加载 web 控件 (ObjectsEditor.ascx)
  • ObjectsEditor.ascx 包含单个自定义控件 (Objects.vb)
  • Objects.vb 将创建另一个自定义控件(ObjectsContainer.vb)并将其添加到它的控件中。ObjectsContainer 需要持久化视图状态。

I'm setting EnableViewState = "true" everywhere i can, but still no result. Do i really need to set those properties here. (ViewStateMode and EnableViewState) If not, where should i handle this and what is the difference between those properties?

我在任何地方都设置了 EnableViewState = "true",但仍然没有结果。我真的需要在这里设置这些属性吗?(ViewStateMode 和 EnableViewState)如果没有,我应该在哪里处理这个问题,这些属性之间有什么区别?

Many thanks.

非常感谢。

采纳答案by ThdK

I can't find why the viewstate did not persist after postback, but I've found another way to hold the value using the controlstate. Here's my implementation:

我不知道为什么在回发后视图状态没有持续存在,但我找到了另一种使用 controlstate 保存值的方法。这是我的实现:

 Public Property SortTime() As DateTime
        Get
            Return _SortTime
        End Get
        Set(ByVal value As DateTime)
            _SortTime = value
        End Set
    End Property

Add the following overridden methods:

添加以下覆盖方法:

    Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        Page.RegisterRequiresControlState(Me)
        MyBase.OnInit(e)
    End Sub

    Protected Overrides Function SaveControlState() As Object
        Return _SortTime
    End Function

    Protected Overrides Sub LoadControlState(ByVal savedState As Object)
        Dim state As DateTime = CType(savedState, DateTime)
        Me._SortTime = state
    End Sub

Give a value to the property in OnLoad

为 OnLoad 中的属性赋值

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        If Not Page.IsPostBack Then
            SortTime = DateTime.Now
        End If
    End Sub

Now i can call the property after the page has loaded and it will always have the value set on the first page load. It will not change on postback and it won't be gone on postback.

现在我可以在页面加载后调用该属性,并且它总是在第一页加载时设置值。它不会在回发时改变,也不会在回发时消失。

I'm sure this is possible with the viewstate too, but for some reason, this was not working for me.

我确信这对于 viewstate 也是可能的,但由于某种原因,这对我不起作用。

Thanks for helping me to understand the Viewstate, I'm sure i'll have to use the viewstate sooner or later.

感谢您帮助我理解 Viewstate,我相信我迟早要使用 viewstate。

回答by Andacious

I see some correct answers here, but I don't see any detailed explanations, so I figured I would chime in:

我在这里看到了一些正确的答案,但我没有看到任何详细的解释,所以我想我会插一句:

ASP.NET has a fairly complicated request/response life-cycle. Each cycle runs through a set of events such as Init, Load, etc.. According to this article, and specifically this image, there is a method called TrackViewState()that executes after the Initevent but before InitCompleteevent. This means that any changes to ViewStatewill not be persisted (tracked) if they are made in the Initevent like the OP has done.

ASP.NET 有一个相当复杂的请求/响应生命周期。通过一组事件,如每个周期运行InitLoad等等。根据本文,并且具体地本图像,有一种叫方法TrackViewState(),该执行后Init事件,但之前InitComplete的事件。这意味着ViewState如果Init像 OP 那样在事件中进行任何更改,则不会保留(跟踪)它们。

There is an additional method called LoadViewState()that takes the ViewStatedata that was posted via the __VIEWSTATEform value and loads it into the current ViewStatecollection. This executes after the InitCompleteevent but before the PreLoadevent. Meaning that values already set to ViewStatebefore LoadViewState()executes will likely be overwritten.

还有一个被调用的额外方法LoadViewState(),它获取ViewState通过__VIEWSTATE表单值发布的数据并将其加载到当前ViewState集合中。这在InitComplete事件之后但在PreLoad事件之前执行。这意味着ViewStateLoadViewState()执行之前已经设置的值可能会被覆盖。

Now, knowing when these 2 events occur, and knowing the ViewStatepersistence methods that execute before and after them, we can deduce that the earliest event where it is safe to set ViewStatevalues is the PreLoadevent. Values set earlier than this event will likely be overwritten and thus not persisted.

现在,知道这两个事件何时发生,以及ViewState在它们之前和之后执行的持久化方法,我们可以推断出可以安全设置ViewState值的最早事件是PreLoad事件。早于此事件设置的值可能会被覆盖,因此不会持久化。

So, to answer your question, set your ViewStatevalue in the OnPreLoad()method or do as others have suggested and do it in the OnLoad()method and your values should be persisted.

因此,要回答您的问题,请ViewStateOnPreLoad()方法中设置您的值或按照其他人的建议执行并在OnLoad()方法中执行,并且您的值应该保持不变。

回答by Tim Schmelter

The page's ViewStatewill not be loaded until Load-event. So you can store your value but not reload it in OnInit.

-eventViewState之前不会加载Load页面。因此,您可以存储您的值,但不能将其重新加载到OnInit.

http://msdn.microsoft.com/en-us/library/ms972976.aspx

http://msdn.microsoft.com/en-us/library/ms972976.aspx

Edit: To be honest, i'm yet not sure what causes your issue(and have not the time to investigate further), but try this way which works as expected:

编辑:老实说,我还不确定是什么导致了您的问题(并且没有时间进一步调查),但是尝试这种按预期工作的方式:

Private Property SortTime As Date
    Get
        If ViewState("PageLoadTimeStamp") Is Nothing Then
            ViewState("PageLoadTimeStamp") = DateTime.Now.AddSeconds(-10)
        End If
        Return DirectCast(ViewState("PageLoadTimeStamp"), Date)
    End Get
    Set(value As Date)
        ViewState("PageLoadTimeStamp") = value
    End Set
End Property

Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
    MyBase.OnInit(e)
    'Me.EnableViewState = True
    'Me.ViewStateMode = System.Web.UI.ViewStateMode.Enabled
    'If Not Page.IsPostBack Then
    '    _SortTime = DateTime.Now
    '    _SortTime.AddSeconds(-10) ' incase the fileserver and webserver date are out of sync
    '    ViewState("PageLoadTimeStamp") = _SortTime
    'End If
End Sub

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    MyBase.OnLoad(e)
    Dim time = SortTime
    '_SortTime = CType(ViewState("PageLoadTimeStamp"), DateTime)
End Sub

回答by Bhaskarreddy Mule

When a postback happens (i.e. when a form is submitted to a server), the variable values that are set in the code-behind page are erased from the memory of the client system

当回发发生时(即当表单提交到服务器时),在代码隐藏页面中设置的变量值将从客户端系统的内存中删除

http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/961985e8-37fe-4b0d-8eb9-9920e4b298d7/

http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/961985e8-37fe-4b0d-8eb9-9920e4b298d7/

回答by Kishore Kumar

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    Me.EnableViewState = True
    Me.ViewStateMode = System.Web.UI.ViewStateMode.Enabled             
    If Not Page.IsPostBack Then
        _SortTime = DateTime.Now                 
        _SortTime.AddSeconds(-10) ' incase the fileserver and webserver date are out of sync                 
         ViewState("PageLoadTimeStamp") = _SortTime                   
    End If 
End Sub 

Write this code

写下这段代码