Can I access ViewState from one page to another page in Asp.Net?

Is there a way to access the page view on another page? Please clarify the answer to clear my doubts, since I think ViewState has a page-only scope and cannot be accessed outside the page.

+3
source share
3 answers

You cannot directly view the ViewState of one page from another page.

If you want to access a specific ViewState value, you can pass the value to the context collection, and then access the value on another page.

On page 1

Context.Items.Add ( "variable" , ViewState["yourvalue"].ToString() );

On page 2

string myValue = Context.Items["variable"].ToString();
+10
source

ASP.NET . , . server.transfer

FirstPage.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["Name"] = "Kamaraj";
        Server.Transfer("SecondPage.aspx");

    }
    public StateBag ReturnViewState()
    {
        return ViewState;
    }

//
Secondpage.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null && PreviousPageViewState != null)
        {
            lblMag.Text = PreviousPageViewState["Name"].ToString();
        }
    }

    private StateBag PreviousPageViewState
    {
        get
        {
            StateBag returnValue = null;
            if (PreviousPage != null)
            {
                Object objPreviousPage = (Object)PreviousPage;
                MethodInfo objMethod = objPreviousPage.GetType().GetMethod("ReturnViewState");//System.Reflection class
                return (StateBag)objMethod.Invoke(objPreviousPage, null);
            }
            return returnValue;
        }
    }
+4

It will also work

FirstPage.aspx (in the code behind)

public void btnTransfer_Click(object sender, EventArgs e)
{
    CompanyInfo comInfo = new CompanyInfo() { ID = 223, Name = "TCS" };
    ViewState["ViewStateCompany"] = comInfo;     
    Server.Transfer("SecondPage.aspx");
}

public CompanyInfo  GetViewValue() 
{
    CompanyInfo comInfo = (CompanyInfo )ViewState["ViewStateCompany"];
    return comInfo;
} 

SecondPage.aspx (in the code behind)

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.PreviousPage != null)
    {

        Type ty = Page.PreviousPage.GetType();
        MethodInfo mi = ty.GetMethod("GetViewValue");
        CompanyInfo comInfo = (CompanyInfo)mi.Invoke(Page.PreviousPage, null);

    }
}

Class CompanyInfo

public class CompanyInfo
{
    public int ID { get; set; }
    public string Name { get; set; }
}
0
source

Source: https://habr.com/ru/post/1736942/


All Articles