简体   繁体   中英

Is it possible to persist the viewstate between pages in ASP.NET?

I have a button (view state enabled) in Master web page and set it to visible=false in one of the child web pages. If a second child page is opened, the button state ( visible=false) is not persisting.

It seems viewstate is only valid for one page and is not transferred to other web pages. Is there some kind of trick to make viewstate global for all web pages?

No, viewstate is page specific. You will need to use something like a session variable or a querystring parameter to pass your state between pages.

No, You cannot make view state global, they are page specific. I would suggest to use cookies if you really want to make it client side otherwise you can use session.

If you need to store on a "global" level, you should be using the Application State. You could also use Cache Object. You may be wanting to pass values from one page to another, you can achieve this by using the Context object in combination with the Server.Transfer.

1) You need a public property on the source page returning the Value to pass

namespace SomeNameSpace
{
    public partial class SourcePage: System.Web.UI.Page
    {
        public string ValueToPass
        {
            get
            {
                if (Context.Items["ValueToPass"] == null)
                    Context.Items["ValueToPass"] = string.Empty;
                return (string)Context.Items["ValueToPass"];
            }
            set
            {
                Context.Items["ValueToPass"] = value;
            }
        }
        ........
    }
}

2) Do a Server.Transfer(DestinationPage.aspx) 3) In the Page_Load event of the destination page

namespace SomeNameSpace
{
    public partial class SourcePage: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var value = this.Context.Items["ValueToPass"];
        }
    }
}

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM