question

moondaddy-8531 avatar image
0 Votes"
moondaddy-8531 asked YijingSun-MSFT edited

ASP.NET page does not hold ViewState

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.


dotnet-aspnet-general
image.png (12.0 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

YijingSun-MSFT avatar image
0 Votes"
YijingSun-MSFT answered YijingSun-MSFT edited

Hi @moondaddy-8531 ,
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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.