ASP.NET page does not hold ViewState

moondaddy 911 Reputation points
2021-03-27T01:57:14.087+00:00

VS 2019, C# 4.8 ASP.NET Webforms, Master/Detail pages:

I have a sample app with:
• 1 button,
• 2 textboxes
• “a” tag with an “href” link.
• asp:HiddenField

Everything is “runat=server”

I can persist data in the hiddenfield and Viewstate across postbacks from the button click, but not from clicking on the “href”. I have a series of “a” tags dynamically created in the page to serve as “paging buttons”. When these are used I cannot persist any variable values.

protected void Page_Load(object sender, EventArgs e)  
{  
    TextBox1.Text = HiddenField1.Value;  
    if (ViewState["test"] != null)  
    {  
        TextBox2.Text = ViewState["test"].ToString();  
    }  
}  
  
protected void Button1_Click(object sender, EventArgs e)  
{  
    HiddenField1.Value = "xxxxx";  
    ViewState["test"] = "It Works";  
}  

81985-image.png

I click on the button the first time and it sets the variable values.

I click on the button the second time and it sets the variable values into the textboxes

I click on the “a” tag and it browses to the same page passing in a parameter for the next page number to go to. And it sets the textbox’s text property to the variable values which is now null.

Any help would be great. Thanks.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,251 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,066 Reputation points
    2021-03-29T07:59:45.797+00:00

    Hi @moondaddy ,
    According to your requirement,I'm guessing that when you redirect to the second page,the value will be postback.
    I suggest you could use session instead of Viewstate. Just like this:

        protected void Page_Load(object sender, EventArgs e)  
        {  
            TextBox1.Text = HiddenField1.Value;  
            if (Session["test"] != null)  
            {  
                TextBox2.Text = Session["test"].ToString();  
            }  
        }  
              
            protected void Button1_Click(object sender, EventArgs e)  
            {  
                HiddenField1.Value = "xxxxx";  
                Session["test"] = "It works";  
            }  
    

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Yijing Sun

    0 comments No comments