开发者

Is there a way to prevent an ASP.Net webapp from clearing out page variables on VB side?

I have a webapp in ASP.Net with a VB codebehind. I need a List variable I have declared to persist as long as the person is on the page, but currently any time a control posts back to t开发者_JAVA百科he code, everything is cleared out. I am completely new to ASP.net, so I have no idea if this is even possible. Can it be done with a Session variable? Those seem to me to be limited to base types, but I could be wrong.


Look into the ASP.NET ViewState. You should also know that lots of gotchas if you do use it including page size bloat and performance issues. The C# code (sry. I'm not good at VB) would be:

List<int> MyList
{
    get { return (List<int>) ViewState["mylist"]; }
    set { ViewState["mylist"] = value; }
}

Note: Don't forget to initialize this variable.

Note on using Session State: This won't work if a user has 2 or more windows open at the same time.


With ASP.Net it is creating a new instance of your Code Behind class each time the page loads, which is why your class-level variables are being reset.

Your best option is probably to store the List you are wanting to hold on to in the Session. If it would make things easier you can create a getter for the list that reads the data from the session variable. In C# it would look like:

private List MyList
{
    get { return Session["ListKey"] as List; }
    set { Session["ListKey"] = value; }
}


If you want to save a variable that is only needed in that particular page, not in any other page, assuming you have a multipage web application, you can use your page ViewState to save variables that you want to persist from request to request.

If you need your variable to persist among different pages, you can use the Session to save it.

Now, when you use your ViewState you must take in account that if you store big objects there, or have many many controls in your page, a huge string (encoded viewstate) goes back and forth between postbacks, increasing the load times and execution times.


Here's the code I ended up using.

Private Property ChangedControls() As List(Of Control)
    Get
        Return DirectCast(Session("changedControls"), List(Of Control))
    End Get
    Set(ByVal value As List(Of Control))
        Session("changedControls") = value
    End Set
End Property

Assigning a new list on page load worked just fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜