ViewState Vs Session … maintaining object through page lifecycle

前端 未结 3 1310
予麋鹿
予麋鹿 2020-12-08 06:24

Can someone please explain the difference between ViewState and Session?

More specifically, I\'d like to know the best way to keep an object available (continuously

相关标签:
3条回答
  • 2020-12-08 07:03

    First of all Viewstate is per page where as the session exists throughout the application during the current session, if you want your searchobject to persist across pages then session is the right way to go.

    Second of all Viewstate is transferred as encrypted text between the browser and the server with each postback, so the more you store in the Viewstate the more data is going down to and coming back from the client each time, whereas the session is stored server side and the only thing that goes back and forth is a session identifier, either as a cookie or in the URL.

    Whether the session or viewstate is the right place to store your search object depends on what you are doing with it and what data is in it, hopefully the above explanation will help you decide the right method to use.

    0 讨论(0)
  • 2020-12-08 07:13

    The view State is page specific, where as Session state is browser specific. You can not able to pass the data from one page to another through view state. But you will do with session state. Each session has some unique ID , Where as View state stored data in hidden fields on page itself.Session store the data on server side, where in view state data stored on page, hence it make the page heavy and application slow. Each control has view state true by default which store its state(control state), we can enable or disable it easily by making enableviewstate=false

    0 讨论(0)
  • 2020-12-08 07:22

    If the search object isn't huge in size, then go with using a ViewState. A ViewState is perfect if you only want the object to live for the current page's lifecycle.

    A session object is also fine to use, but obviously once the search object is in there, it will be around for longer the page's lifecycle.

    Also, one thing I do with ViewState/Session objects is wrap their access with a property:

    public object GetObject
    {
        get
        {
            return ViewState["MyObject"];
        }
        set
        {
            ViewState["MyObject"] = value;
        }
    }
    

    I tend to find it cleaner to do it this way. Just change the above code to fit your needs.

    • Source 1

    • Source 2

    0 讨论(0)
提交回复
热议问题